How do I access a field on a struct which is not always in the same level?

2 ビュー (過去 30 日間)
Ana
Ana 2018 年 6 月 27 日
編集済み: Ana 2018 年 6 月 27 日
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 件のコメント
Ana
Ana 2018 年 6 月 27 日
Yes, that would be one option.
The problem is that I am using this quite often in the code so it would be more recommendable if I could avoid filling it of "if" statements if there is the possibility.
Thanks in any case for the suggestion.
KSSV
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
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
  1 件のコメント
Ana
Ana 2018 年 6 月 27 日
編集済み: Ana 2018 年 6 月 27 日
Perfect! Thank you very much for the answer.

サインインしてコメントする。

その他の回答 (1 件)

Stephen23
Stephen23 2018 年 6 月 27 日
編集済み: Stephen23 2018 年 6 月 27 日
This is easy with getfield, you just need to define a cell array of the required fieldnames:
>> var1.subfield1 = 1;
>> var2.field1.subfield1 = 3;
>> c1 = {'subfield1'};
>> c2 = {'field1','subfield1'};
>> getfield(var1,c1{:})
ans = 1
>> getfield(var2,c2{:})
ans = 3
  1 件のコメント
Ana
Ana 2018 年 6 月 27 日
Thanks for the answer! In the use I was making in my code, having a function was more appropriate, so I finally used Jan's answer, but this is also very useful for some other problems I may face in the future.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeStructures についてさらに検索

製品


リリース

R2016b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by