Reputation: 121
Let's say I'm creating the following struct in Matlab:
spec.Property1 = 0
spec.Property2 = 0
spec.Property3.Name = 0
spec.Property3.Something = ''
It's working and I'm getting my expected struct:
Property1: 0
Property2: 0
Property3: [1×1 struct]
Let's say i want to do this:
nameOfNewStruct1 = 'Property1'
nameOfNewStruct2 = 'Property2'
nameOfNewStruct3 = 'Property3.Name'
nameOfNewStruct4 = 'Property3.Something'
spec.(nameOfNewStruct1) = 0
spec.(nameOfNewStruct2) = 0
spec.(nameOfNewStruct3) = 0
spec.(nameOfNewStruct4) = ''
Invalid field name: 'Property3.Name'.
why is it not working? Do need to change the settings if i want to use a 'Something.Something' char?
Thanks!
Upvotes: 0
Views: 1010
Reputation: 1390
From Loren (check comments around #20 in 2011) https://blogs.mathworks.com/loren/2005/12/13/use-dynamic-field-references/, this is (was?) not possible in the way you are attempting. A simple solution would be to do equivalent of spec.('Property3').('Name')
.
How to do it in a similar way to yours, with arbitrary depth, is answered in a later comment.
A.l1.l2.l3.l4 = 1234;
fieldname = 'l1.l2.l3.l4';
eval(['A.',fieldname])
Upvotes: 1