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

30 ビュー (過去 30 日間)
Mario Goldenbaum
Mario Goldenbaum 2018 年 8 月 23 日
移動済み: Eric Sargent 2023 年 12 月 7 日
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
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.
Mario Goldenbaum
Mario Goldenbaum 2018 年 8 月 24 日
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.

サインインしてコメントする。

採用された回答

Adam Danz
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
  1 件のコメント
Mario Goldenbaum
Mario Goldenbaum 2018 年 8 月 24 日
移動済み: Eric Sargent 2023 年 12 月 7 日
Hi Adam,
Thanks much for this. It works.
Best, M.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeStructures についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by