MATLAB: Is there a MATLAB function that can check if a field exists in a MATLAB structure

checkfieldisfieldm-structMATLABmemberstructstructure

The 'exist' function returns true if a structure with a particular name exists. The 'isfield' function returns true if a field is in a structure array. However, I would like a function that determines if a field exists anywhere in a structure of structures. For example, in the following code, the 'isfield' function does not identify that "c" is a field of "a".
a.b.c = 1;
isfield(a, 'c')
results in:
ans =
0

Best Answer

There is no MATLAB function that examines every level of a structure of structures, or nested structure, to determine if a field exists. The 'isfield' function examines only the top level of a nested structure. To determine if a field exists at any other level, you can use either of the following methods.
1. To determine if a field exists in a particular substructure, use 'isfield' on that substructure instead of the top level. In the example, the value of a.b is itself a structure, and you can call 'isfield' on it.
a.b.c = 1;
isfield(a.b,'c')
ans =
logical
1
Note: If the first input argument is not a structure array, then 'isfield' returns 0 (false). While there are other MATLAB data types that have properties you can access with dot notation, those other data types are not structure arrays.
2. To determine if a field exists at any level in a nested structure, create a new function that examines all levels of the structure. Open the MATLAB Editor and paste the following function into it. Save the function as a MATLAB file, named 'myIsField.m'.
function isFieldResult = myIsField (inStruct, fieldName)
% inStruct is the name of the structure or an array of structures to search
% fieldName is the name of the field for which the function searches
isFieldResult = 0;
f = fieldnames(inStruct(1));
for i=1:length(f)
if(strcmp(f{i},strtrim(fieldName)))
isFieldResult = 1;
return;
elseif isstruct(inStruct(1).(f{i}))
isFieldResult = myIsField(inStruct(1).(f{i}), fieldName);
if isFieldResult
return;
end
end
end
Call 'myIsField' on a nested structure.
a.b.c = 1;
myIsField(a,'c')
ans =
logical
1