필터 지우기
필터 지우기

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 CenterFile Exchange에서 Structures에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by