How to access multiple fields in a struct by a vector of indices?
29 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Mario Goldenbaum
am 23 Aug. 2018
Verschoben: Eric Sargent
am 7 Dez. 2023
Hi Everyone,
I have a struct
a
with fields that is of the form:
f1: [5×5 double]
f2: [5×5 double]
f3: [5×5 double]
f4: [5×5 double]
f5: [5×5 double]
I also have a vector of indices
idx = [2,3,4]
and would like to access/extract the fields in a indexed by idx (i.e., f2,f3,f4). Is there a clever and convenient way to accomplish this without using, for instance, fieldnames in combination with a for loop?
Thanks and all best,
M.
2 Kommentare
Stephen23
am 24 Aug. 2018
Bearbeitet: Stephen23
am 24 Aug. 2018
"Is there a clever and convenient way to accomplish this without using, for instance, fieldnames in combination with a for loop?"
Not really, because fields are not designed to represent a particular sequence - their order can be changed, without changing their names. A sequence is best represented by an index: its order is fixed, simply by definition of the index itself. This means the two are not equivalent, and there is no general solution to convert between fieldnames and indices.
If you want to access something with indices, then why are you using fieldnames? Probably you should instead be using a non-scalar structure with efficient indexing, and avoid using slow numbered fieldnames altogether.
Akzeptierte Antwort
Adam Danz
am 23 Aug. 2018
There isn't a set method but here are some options.
Option 1 : Convert to cell array
sCell = struct2cell(s)
sCell(idx)
Option 2: Use a non-scalar structure instead
1 Kommentar
Weitere Antworten (0)
Siehe auch
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!