How to access multiple fields in a struct by a vector of indices?
30 次查看(过去 30 天)
显示 更早的评论
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 个评论
Stephen23
2018-8-24
编辑:Stephen23
2018-8-24
"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.
采纳的回答
Adam Danz
2018-8-23
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
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Structures 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!