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

26 visualizaciones (últimos 30 días)
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');

Respuesta aceptada

MathWorks Support Team
MathWorks Support Team el 25 de Oct. de 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')

Más respuestas (1)

Steven Lord
Steven Lord el 16 de Dic. de 2022
Another approach that uses neither eval nor repeated calls to isfield is to use getfield.
a.b.c = 1;
isNestedField(a, 'b.c')
ans = logical
1
isNestedField(a, 'b.d')
ans = logical
0
isNestedField(1:10, 'a')
ans = logical
0
function tf = isNestedField(s, thefields)
fieldlist = split(thefields, '.');
try
getfield(s, fieldlist{:});
tf = true;
catch
tf = false;
end
end

Categorías

Más información sobre Structures en Help Center y File Exchange.

Etiquetas

Aún no se han introducido etiquetas.

Productos


Versión

R2012a

Community Treasure Hunt

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

Start Hunting!

Translated by