Is it possible to check for existence of fields in nested structures with isfield in MATLAB 8.1 (R2013a)?
89 views (last 30 days)
I have the following structure
a.b.c = 1;
I know it is possible to search for the nested
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.
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')
More Answers (2)
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:
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 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
S (1,1) struct
FIELD (1,1) string
SUBFIELD = strsplit(FIELD,'.');
if numel(SUBFIELD) == 1
tf = isfield(S,FIELD);
tf = true;
for i = 2:numel(SUBFIELD)
S = S.(SUBFIELD(i-1));
tf = false;