|
Below are some functions that I used to use for this kind of thing before the days of dynamic fieldnames (or at least before I was aware of them). It combines Jan's try...catch idea with eval()
I never find use for them anymore and, on the whole, I find it wise to avoid deep nesting of structures.
function Y=getfld(S,fieldpath)
%A somewhat enhanced version of getfield() allowing one to get
%field values in subfields of the structure/object S by specifying the FIELDPATH.
%
%Usage: getfld(S,'s.f') will get S.s.f
%
%Works for any object capable of a.b.c.d ... subscripting
%
%Currently, only single structure input is supported, not structure arrays.
cmdstr=['S.' fieldpath ';'];
try
Y=eval(cmdstr);
catch
error 'Bad fieldpath';
end
function S=setfld(S,fieldpath,V)
%A somewhat enhanced version of setfield() allowing one to set
%fields in substructures of structure/object S by specifying the FIELDPATH.
%
%Usage: setfld(S,'s.f',V) will set S.s.f=V
%
%
%%Note that for structure S, setfield(S.s,'f') would crash with an error if
%S.s did not already exist. Moreover, it would return a modified copy
%of S.s rather than a modified copy of S, behavior which would often be
%undesirable.
%
%
%Works for any object capable of a.b.c.d ... subscripting
%
%Currently, only single structure input is supported, not structure arrays.
try
eval(['S.' fieldpath '=V;']);
catch
error 'Something''s wrong.';
end
|