フィルターのクリア

Can I use a variable string to index into a structure?

98 ビュー (過去 30 日間)
Victor
Victor 2022 年 3 月 30 日
コメント済み: Steven Lord 2022 年 3 月 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")

採用された回答

Voss
Voss 2022 年 3 月 30 日
I think what you want is dynamic field names.
% An example struct:
S = struct('OptionA',1,'OptionB',2)
S = struct with fields:
OptionA: 1 OptionB: 2
choice = "OptionB";
S.(choice)
ans = 2
% Another one, more like yours, and a function f to do the field accessing:
Structure = struct('Level1',struct('OptionC',9))
Structure = struct with fields:
Level1: [1×1 struct]
f = @(x) Structure.Level1.(x) % note the parentheses
f = function_handle with value:
@(x)Structure.Level1.(x)
f("OptionC")
ans = 9
  1 件のコメント
Steven Lord
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 = struct with fields:
s: [1×1 struct]
x.s
ans = struct with fields:
x: 1 y: 2
x.('s').('y') % or
ans = 2
getfield(x, 's', 'y')
ans = 2
f = {'s', 'y'};
getfield(x, f{:})
ans = 2

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

その他の回答 (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