Reputation: 58
I have a data structure A.B.C and I want to access some of its parts dynamically reading the object names from a cell array populated by importing csv file.
For example, my data structure has following fields A.B.C
within B are B1, B2, B2, B3, B4, B5
within C are field_1, field_3, field_3
Names cell array with all the possibilities for B, imported from cvs
I want to access dynamically field_2 for each B case. I imported the names from csv file and tried to pass the names like:
A.(Names(1,1)).field_2
but get an error
'Argument to dynamic structure reference must evaluate to a valid field name.'
When I print the single names of the array the apostrophes are there. For example Names(1,1) returns 'B1' not B1
How can I bypass the apostrophes? or is it a better way to reference the objects?
Upvotes: 0
Views: 168
Reputation: 570
I'm building off of emzet's comment, and providing a reproducible example, showing how this will work. Here's my code to re-create your structure:
A = struct();
A.B1 = struct();
A.B2 = struct();
A.B3 = struct();
A.B4 = struct();
A.B1.field_1 = 'testB1C1';
A.B1.field_2 = 'testB1C2';
A.B1.field_3 = 'testB1C3';
A.B1.field_4 = 'testB1C4';
A.B2.field_1 = 'testB2C1';
A.B2.field_2 = 'testB2C2';
A.B2.field_3 = 'testB2C3';
A.B2.field_4 = 'testB2C4';
A.B3.field_1 = 'testB3C1';
A.B3.field_2 = 'testB3C2';
A.B3.field_3 = 'testB3C3';
A.B3.field_4 = 'testB3C4';
NamesB = {'B1', 'B2', 'B3' ,'B4'};
NamesC = {'field_1', 'field_2', 'field_3' ,'field_4'};
Now, as you've indicated, doing this:
A.(NamesB(1)).(NamesC{1})
will return an error:
Argument to dynamic structure reference must evaluate to a valid field name.
If you do this, instead:
A.(NamesB{1}).(NamesC{1}) % notice the curly braces after NamesB.
ans =
'testB1C1'
will provide the right value.
Upvotes: 1