checking if a nested field exists

15 ビュー (過去 30 日間)
A
A 2020 年 12 月 30 日
コメント済み: Stephen23 2020 年 12 月 30 日
I have a nested field A.B.C and I would like to check if C exists.
B changes and has a different name depending on what file I use so I can’t do isfield(A.B,C), but I know what B is in this way:
isfield(['A.' D.E.F{i}],'C')
This should give me logical=1, but it gives 0 and I don’t understand why. Any help is much appreciated!
Thanks in advance
  1 件のコメント
Stephen23
Stephen23 2020 年 12 月 30 日
"This should give me logical=1, but it gives 0 and I don’t understand why. "
Character vectors do not have fields.

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

採用された回答

Jan
Jan 2020 年 12 月 30 日
編集済み: Jan 2020 年 12 月 30 日
In your code:
isfield(['A.' D.E.F{i}],'C')
what is D.E.F{i}? A concatenation with 'A.' will create a char vector. Char vectors are no structs, so isfield replies false as expected.
Try this instead:
% Some test data:
A1.B.C = 1;
A2.AnyStuff = '?';
A2.FunnyName.C = 2;
A3.HasNoC.D = 3;
A3.Nonsense = {};
% TRUE if subfield is existing:
hasSubField(A1, 'C')
hasSubField(A2, 'C')
hasSubField(A3, 'C')
function T = hasSubField(S, F)
T = false;
Data = struct2cell(S);
for k = 1:numel(Data)
if isfield(Data{k}, F)
T = true;
return;
end
end
end
This searchs for a subfield in the first level. If any of the fields is a struct and contains the field provided by the input F, true is replied. Or are you searching for deeply nested structs also?

その他の回答 (0 件)

カテゴリ

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

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by