Check for existence of nested fields
Ältere Kommentare anzeigen
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 Kommentare
per isakson
am 8 Nov. 2016
What's wrong with
try
do_something(topstruct.f1.f2.fleaf)
catch me
% find out what happened
end
Michael Schwager
am 11 Nov. 2016
Stephen23
am 18 Mai 2020
See:
Akzeptierte Antwort
Weitere Antworten (0)
Kategorien
Mehr zu Variables finden Sie in Hilfe-Center und File Exchange
Produkte
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!