How do I access a field on a struct which is not always in the same level?
조회 수: 2 (최근 30일)
이전 댓글 표시
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
KSSV
2018년 6월 27일
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;
채택된 답변
Jan
2018년 6월 27일
편집: Jan
2018년 6월 27일
Create a function which checks the existence of the subfield:
function Data = getSubField(S, F1, F2)
if isfield(S, F2)
Data = S.(F2);
elseif isfield(S, F1)
Data = S.(F1).(F2);
else
Data = [];
end
Now call this like:
var1.subfield1 = 1;
var2.field1.subfield1 = 3;
Data1 = getSubField(var1, 'field1', 'subfield1');
Data2 = getSubField(var2, 'field1', 'subfield1');
If run-time matters, this might be faster - or slower (try it by your own):
function Data = getSubField(S, F1, F2)
try
Data = S.(F2);
catch
try
Data = S.(F1).(F2);
catch
Data = [];
end
end
참고 항목
카테고리
Help Center 및 File Exchange에서 Structures에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!