Access Sub-fields of multiple different-named fields in struct

36 ビュー (過去 30 日間)
Nathan Moorman
Nathan Moorman 2022 年 9 月 30 日
回答済み: Walter Roberson 2022 年 9 月 30 日
I am trying to find an efficient way to grab data from lower-level fields of a struct. The top-level struct, s, has fields a, b, c, and each of those has different subfields, but they all share subfield x. Ideally, I would like to have a single line that would let me get a vector or cell of those values, something like:
>> out = s.([a,b,c]).x;
>> out = {'str1', 'str2', 'str3'}
So far, the best way I have come up with is:
out = cell(1,3);
f = fieldnames(s);
for i = 1:3
out{i} = s.(f{i}).x;
end
But it seems like there should be a better, ideally loop-free, way to do this. Any ideas?

回答 (2 件)

Walter Roberson
Walter Roberson 2022 年 9 月 30 日
struct2cell(structfun(@(F)F.x, s, 'UniformOutput', 0))

Cel Kulasekaran
Cel Kulasekaran 2022 年 9 月 30 日
If you want to access a dynamic structure, s, it must evaluate to a single valid field name. I don't think there is much penalty in the loop here, do you have control of the construction of s? Perhaps re-consider that datastructure.

カテゴリ

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

製品


リリース

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by