Can I use a variable string to index into a structure?
96 views (last 30 days)
Show older comments
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 Comments
Accepted Answer
Voss
on 30 Mar 2022
% 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 Comment
Steven Lord
on 30 Mar 2022
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{:})
More Answers (0)
See Also
Categories
Find more on Structures in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!