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

Matlab Structures: How can I pass a concatenated string as a field to a structure?

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

I have a structure XYZ containing information about elements 01 to 04. I need to read or write to the elements based on the provided instance ("inst") number. Matlab gives the error "Reference to non-existent field 'strcat' or 'element'. I understand why Matlab gives the error. Trying to figure out how could I pass the field information to read or write to the element?

% 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
0
42.3k 2020-11-30 06:30:11

To access different fields you can use () around the Field_Name to be accessed.

% 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);