Check for existence of nested fields

6 visualizaciones (últimos 30 días)
Michael Schwager
Michael Schwager el 8 de Nov. de 2016
Comentada: Stephen23 el 18 de Mayo de 2020
I have a struct with some nested fields, such as cfg.accel.filename, cfg.accel.calibration, cfg.gyro.filename, etc. Sometimes the fields exist, sometimes they don't, at different levels. In the above example, the 'gyro' field could be missing, or it could just be cfg.accel.calibration that could be missing.
Is there a way to check for deeply nested fields? Currently I'm doing something like:
topstruct = struct(whatever...)
if isfield(topstruct, 'f1')
if isfield(topstruct.f1, 'f2')
if isfield(topstruct.f2, 'fleaf')
do_something(topstruct.f1.f2.fleaf)
end
end
end
Ideally I'd like to do some sort of thing like doifget(mystruct, action, field1, field2,...) where action is not actually evaluated unless mystruct.field1.field2 exists. Maybe action can be a lambda/anonymous function.
Probably just something like getif(mystruct, field1, field2, ...) returns [] if the field doesn't exist, and the value if it does.
  3 comentarios
Michael Schwager
Michael Schwager el 11 de Nov. de 2016
I think that would probably work, but I guess using try/catch for non-errors is something I come to understand as a questionable practice. I can try it and see how the code ends up looking.

Iniciar sesión para comentar.

Respuesta aceptada

Thorsten
Thorsten el 10 de Nov. de 2016
You can use my function isnestedfield:
function yn = isnestedfield(s, fields)
%ISNESTEDFIELD True if nested fields are in a structure.
% ISNESTEDFIELD(S,FIELDs) returns true if the string FIELDs is containes
% nested fields of S in the format of a single string of fieldnames
% separated by '.'
%
%Example:
% Check if s.f1.f11.f111 is a field:
% isfield(s, 'f1.f11.f111')
%
% Thorsten.Hansen@psychol.uni-giessen.de 2016-11-10
% extract fields
field = textscan(fields, '%s', 'delimiter', '.');
field = field{1};
yn = true;
structstr = 's'; % name of first input parameter
i = 1;
while yn && i <= numel(field)
% disp(['yn = isstruct(' structstr ')'])
eval(['yn = isstruct(' structstr ');']);
if yn
% disp(['yn = isfield(' structstr ', ' field{i} ')'])
eval(['yn = isfield(' structstr ', field{i});']);
end
if yn
structstr = strcat(structstr, '.', field{i});
i = i + 1;
end
end

Más respuestas (0)

Categorías

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

Etiquetas

Productos

Community Treasure Hunt

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

Start Hunting!

Translated by