Warm tip: This article is reproduced from serverfault.com, please click

其他-Matlab结构:如何将串联字符串作为字段传递给结构?

(其他 - Matlab Structures: How can I pass a concatenated string as a field to a structure?)

发布于 2020-11-29 20:19:33

我有一个结构XYZ,其中包含有关元素01到04的信息。我需要根据提供的实例(“实例”)编号读取或写入这些元素。Matlab给出错误“对不存在的字段'strcat'或'element'的引用。我理解为什么Matlab出现错误。想弄清楚如何传递字段信息以读取或写入元素?

% XYZ structure
XYZ.Element_1 = 1;
XYZ.Element_2 = 5;
XYZ.Element_3 = 6;
XYZ.Element_4 = 7;

%Instance number
inst='1'

%Concatenate instance information to obtain the field
element=strcat('Element_', inst);

%Read the value of Element_1
var1=XYZ.strcat('Element_', inst);
var2=XYZ.element;

Questioner
Vinod
Viewed
11
42.3k 2020-11-30 06:30:11

要访问不同的字段,你可以()在周围使用Field_Name进行访问。

% XYZ structure
XYZ.Element_1 = 1;
XYZ.Element_2 = 5;
XYZ.Element_3 = 6;
XYZ.Element_4 = 7;

inst = '1';
Field_Name = strcat('Element_', inst);
var1 = XYZ.(Field_Name);
    
inst = '2';
Field_Name = strcat('Element_', inst);
var2 = XYZ.(Field_Name);