How do I access a field on a struct which is not always in the same level?
Show older comments
Hello,
I have a problem in generalizing a code for different structure contents. The problem is that I need to access a field (let's say subfield1) which is not always in the same level of the structure.
var1.subfield1 = 1;
var2.field1.subfield1 = 3;
I would like to be able to define a variable, fieldname, that would be empty for var1 and 'field1' for var2, so that:
var1.(fieldname).subfield1
var2.(fieldname).subfield1
would work and give me the value of that field. However if I set:
fieldname=''
and try to execute the first line, this gives an error:
Reference to non-existent field ''.
I have also tried using the getfield function, with no success.
Is there any solution for this, or should the structures have the same fields from the beginning to be able to do this?
Thank you very much in advance,
Ana Gómez
3 Comments
Ameer Hamza
on 27 Jun 2018
What about treating this as a special case and adding an if statement.
if ~isempty(fieldname)
var1.(fieldname).subfield1
else
var1.subfield1
end
Ana
on 27 Jun 2018
KSSV
on 27 Jun 2018
Why don't you create some dummy filedname.....this dummy filedname will be already known to you....
var1.dummy.subfield1 = 1;
var2.field1.subfield1 = 3;
Accepted Answer
More Answers (1)
>> var1.subfield1 = 1;
>> var2.field1.subfield1 = 3;
>> c1 = {'subfield1'};
>> c2 = {'field1','subfield1'};
>> getfield(var1,c1{:})
ans = 1
>> getfield(var2,c2{:})
ans = 3
Categories
Find more on Structures in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!