I have an array of objects of type Peak. Given the name of a field (I will be using several in turn), I would like to get the value of that field for every object in the array, resulting in a vector of double. Is there any way to ask getfield to do that, without resorting to a for loop? Or is there some related function that would do the job for me?

 採用された回答

Bruno Luong
Bruno Luong 2024 年 3 月 29 日

0 投票

Create 1 x 3 struct array with field named 'afield'
s = struct('afield', {11 12 13})
s = 1x3 struct array with fields:
afield
s(1)
ans = struct with fields:
afield: 11
s(2)
ans = struct with fields:
afield: 12
s(3)
ans = struct with fields:
afield: 13
% Here is the command that might be usefule for you
A = cat(2, s.afield)
A = 1x3
11 12 13
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>

3 件のコメント

Ken
Ken 2024 年 3 月 29 日
Yes, but not quite. I need to reference the field name as a quoted string, because the same code will be applied to several different fields, as the user selects which one to graph.
Bruno Luong
Bruno Luong 2024 年 3 月 29 日
編集済み: Bruno Luong 2024 年 3 月 29 日
Take a look at dynamic fieldname
s = struct('afield', {11 12 13});
fieldname = "afield"
fieldname = "afield"
A = cat(2, s.(fieldname))
A = 1×3
11 12 13
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
Ken
Ken 2024 年 3 月 30 日
Well I'll be! That is some WEIRD syntax! But it fits my need perfectly. Thank you!

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

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File Exchange で Structures についてさらに検索

製品

リリース

R2023b

質問済み:

Ken
2024 年 3 月 29 日

コメント済み:

Ken
2024 年 3 月 30 日

Community Treasure Hunt

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

Start Hunting!

Translated by