# Is it possible to check for existence of fields in nested structures with isfield in MATLAB 8.1 (R2013a)?

71 ビュー (過去 30 日間)
MathWorks Support Team 2013 年 10 月 25 日

I have the following structure
a.b.c = 1;
I know it is possible to search for the nested
isfield(a.b,'c')
But I would like to check for the existence of the field 'c' even when I am not sure that the field 'b' exists, e.g.
isfield(a,'b.c');

### 採用された回答

MathWorks Support Team 2013 年 10 月 25 日
There is no MATLAB function to determine the existence of fields in nested structures. The only workaround is to check separately for the existence of 'b' and of 'c':
isfield(a, 'b') && isfield(a.b, 'c')
##### 1 件のコメント表示非表示 なし
Benoît Béranger 2018 年 9 月 25 日
Let's say you have the following structure :
a.b.c.d.e.f.g.h.i.j.K = 1;
This solution is not elegant :
isfield(a, 'b') && isfield(a.b, 'c') && isfield(a.b.c, 'd') ...
You need another strategy, like something recursive.

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

### その他の回答 (2 件)

Tom 2014 年 2 月 12 日

Or if, like me, you don't want to do a ton of isfield()s on a deeply nested structure, you can shortcut to testing the last one like this:
eval('isfield(a.b.c.d.e.f,''g'')','0')
Of course, in the example I tried, this took 5 times longer than the multiple isfield method, so you have to decide if you need the speed or easier to read code. (Also, the deeper the nesting gets, the more efficient this version gets relative to multiple calls to isfield.) Furthermore, the eval() statement might also allow you to skip the 'if' entirely if you're just wanting to get the value of your nested field/assign a default value, e.g.
MyData = eval('a.b.c.d.e.f.g','NaN');
##### 1 件のコメント表示非表示 なし
Matt J 2014 年 2 月 12 日
Might be faster if you do
try
eval('a.b.c.d.e.f.g');
tf=true;
catch
tf=false;
end

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

Geoff McVittie 2020 年 9 月 4 日

For later releases of MATLAB, another strategy is to create your own issubfield function. The issubfield has the advantage of not calling eval and can handle any depth. Enjoy!
function tf = issubfield(S,FIELD)
%ISSUBFIELD Determine if FIELD is valid in struct S
% Determine if the specified FIELD or nested FIELD is present in the
% given structure.
%
% A.b.c.d = 1;
% issubfield(A,"b.c.d") % TRUE
% issubfield(A,"b") % TRUE
% issubfield(A,"b.c.d.e") % FALSE
% issubfield(A,"f") % FALSE
arguments
S (1,1) struct
FIELD (1,1) string
end
SUBFIELD = strsplit(FIELD,'.');
if numel(SUBFIELD) == 1
tf = isfield(S,FIELD);
return;
end
tf = true;
for i = 2:numel(SUBFIELD)
S = S.(SUBFIELD(i-1));
if ~isfield(S,SUBFIELD(i))
tf = false;
break;
end
end
end

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

タグが未入力です。

R2012a

### Community Treasure Hunt

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

Start Hunting!