MATLAB Answers

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

77 views (last 30 days)
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');

Accepted Answer

MathWorks Support Team
MathWorks Support Team on 25 Oct 2013
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 Comment

Benoît Béranger
Benoît Béranger on 25 Sep 2018
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.

Sign in to comment.

More Answers (2)

Tom
Tom on 12 Feb 2014
Edited: Tom on 12 Feb 2014
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');

Geoff McVittie
Geoff McVittie on 4 Sep 2020
Edited: Geoff McVittie on 4 Sep 2020
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

  0 Comments

Sign in to comment.

Tags

No tags entered yet.

Products


Release

R2012a

Community Treasure Hunt

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

Start Hunting!