Effacer les filtres
Effacer les filtres

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

98 vues (au cours des 30 derniers jours)
Victor
Victor le 30 Mar 2022
Commenté : Steven Lord le 30 Mar 2022
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")

Réponse acceptée

Voss
Voss le 30 Mar 2022
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 commentaire
Steven Lord
Steven Lord le 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 = 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

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Structures dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by