How to access multiple fields in a struct by a vector of indices?
30 views (last 30 days)
Show older comments
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 Comments
Stephen23
on 24 Aug 2018
Edited: Stephen23
on 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.
Accepted Answer
Adam Danz
on 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
More Answers (0)
See Also
Categories
Find more on Structures in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!