Can I use a variable string to index into a structure?
96 ビュー (過去 30 日間)
古いコメントを表示
I have a multi-layer structure Structure.Level1 - Structure.Level10.
Within each of the levels there are fields OptionA - OptionG which correspond to a certain value, e.g. Structure.Level1.OptionA might be = 0.5.
I have a variable which reflects a user choice between OptionA - OptionG, e.g. choice = "OptionC". Is there a way to use this variable to dot index into the structure? So if the user were to select "OptionC", I would like to loop through each of the Levels and extract the OptionC value from each.
I attempted to make use of a function handle as follows:
f = (@x) Structure.Level1.x
f("OptionC")
0 件のコメント
採用された回答
Voss
2022 年 3 月 30 日
% An example struct:
S = struct('OptionA',1,'OptionB',2)
choice = "OptionB";
S.(choice)
% Another one, more like yours, and a function f to do the field accessing:
Structure = struct('Level1',struct('OptionC',9))
f = @(x) Structure.Level1.(x) % note the parentheses
f("OptionC")
1 件のコメント
Steven Lord
2022 年 3 月 30 日
Dynamic field names is one approach. The getfield function is another and may be better in this case with multiple levels of indexing, since you don't need to know when you write the code how many levels of nesting your struct has. Build a cell array with the appropriate number of elements then use it as a comma-separated list to pass the appropriate number of inputs to getfield.
x = struct('s', struct('x', 1, 'y', 2))
x.s
x.('s').('y') % or
getfield(x, 's', 'y')
f = {'s', 'y'};
getfield(x, f{:})
その他の回答 (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!