matlab - Dynamically check for existence of structure field name with hierarchy -


as follow-up previous question how assign fields structure variable dynamic hierarchy, able query fields isfield. however, isfield take 1 argument, not list setfield.

to summarize problem: have function organizes data structure variable. depending on flags, data saved substructures different number of levels.

for instance, accepted answer previous question has me doing build structure:

foo = struct();  % pick one... true_false_statement = true; % true_false_statement = false;  if true_false_statement     extra_level = {}; else     extra_level = {'baz'}; end  foo = setfield(foo, extra_level{:}, 'bar1', 1); 

which gives me foo.bar1 = 1 if true_false_statement true, , foo.baz.bar1 = 1 otherwise.

now want test existence of field (for instance pre-allocate array). if this:

if ~isfield(foo, extra_levels{:}, 'bar1')     foo = setfield(foo, extra_level{:}, 'bar1', zeros(1,100)); end 

i error because isfield accept 2 arguments.

the best i've been able come write separate function try...catch block.

function tf = isfield_dyn(structure_variable, intervening_levels, field) try     getfield(structure_variable, intervening_levels{:}, field);     tf = true; catch err     if strcmpi(err.identifier, 'matlab:nonexistentfield')         tf = false;     else         rethrow(err);     end end 

as mentioned below in comments, hacky hack way this, , doesn't work well.

is there more elegant built-in way this, or other more robust way write custom function this?

you might find private utility functions getsubfield, setsubfield, rmsubfield, , issubfield fieldtrip toolbox handy. documentation of getsubfield:

% getsubfield returns field structure standard % getfield function, except can specify nested fields % using '.' in fieldname. nesting can arbitrary deep. % % use %   f = getsubfield(s, 'fieldname') % or %   f = getsubfield(s, 'fieldname.subfieldname') % % see getfield, issubfield, setsubfield 

Comments

Popular posts from this blog

searchKeyword not working in AngularJS filter -

sequelize.js - Sequelize: sort by enum cases -

user interface - how to replace an ongoing process of image capture from another process call over the same ImageLabel in python's GUI TKinter -