Invoke Structure Fields using Variables in MATLAB

Jul. 30, 2022

在MATLAB中,通过变量获得结构体的字段值。比如,有一个结构体s,它分别有abe 三个字段,字段值分别为1.02.03.0。现在想借助一个变量来获得字段e的值:

1
2
3
4
5
6
7
% Define a structure
s.a = 1.0;
s.b = 2.0;
s.e = 3.0;

% Variable index
variable = 'e';

一开始想到使用 eval() 函数,但是系统无法识别这样的表达:

1
2
3
>> s.eval(variable)

Unrecognized field name "eval".

后来找到可以使用 MATLAB 的 getfield() 函数 [1]

1
2
3
4
>> getfield(s, variable)

ans =
    3

但是,其实 MATLAB 提供了一种更简单的方法通过变量来创建或使用字段 [2]:

1
2
3
4
>> s.(variable)

ans =
     3


References

[1] getfield - MATLAB Documentation

[2] Generate Field Names from Variables