How to access multiple fields in a struct by a vector of indices?

29 Ansichten (letzte 30 Tage)
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
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.
Mario Goldenbaum
Mario Goldenbaum am 24 Aug. 2018
Stephen, thanks much for your comment. I agree with you. The simple answer is that I got tons of data stored this way. And now I have to deal with it.

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

Adam Danz
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

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