How to extract a field from a structure?

187 Ansichten (letzte 30 Tage)
sarah wentzel
sarah wentzel am 5 Apr. 2022
Kommentiert: RST am 3 Aug. 2023
I want to extract an entire field from structures with multiple fields and store it in a vector:
vector = S.(sample)
only returns me row 1
vector = S(2).data
This would return me the second position but when I try to extract all the data
vector = S.data
or
vector = S(:).data
I still get only 24x250x50 double, and not all the data column.
Thank you!

Akzeptierte Antwort

Voss
Voss am 5 Apr. 2022
% making a struct array with two fields:
S = struct('sample',num2cell(1:10),'info',sprintfc('information_%d',1:10))
S = 1×10 struct array with fields:
sample info
% get the 'sample' field from each element of S, put them in a vector:
vector = [S.sample]
vector = 1×10
1 2 3 4 5 6 7 8 9 10
% get the 'info' field from each element of S, put them in a cell array:
cell_array = {S.info}
cell_array = 1×10 cell array
{'information_1'} {'information_2'} {'information_3'} {'information_4'} {'information_5'} {'information_6'} {'information_7'} {'information_8'} {'information_9'} {'information_10'}
  3 Kommentare
Voss
Voss am 3 Aug. 2023
@RST: FYI, compose is the documented built-in function that operates similarly to sprintfc.
compose('information_%d',1:3)
ans = 1×3 cell array
{'information_1'} {'information_2'} {'information_3'}
It's also worth pointing out that string concatenation is convenient in some contexts.
"information_" + (1:3)
ans = 1×3 string array
"information_1" "information_2" "information_3"

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Structures finden Sie in Help Center und File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by