Clever way to assign multiple fields at once?
Due to legacy function calls I'm sometimes forced to write ugly wrappers like this
function return = someWrapper(someField)
a = someField.a;
b = someField.b;
% and so on, realistically it's more like ten variables that
% could actually be grouped in a struct
save('params.mat', 'a', 'b'); %etc.
% then, on another machine, a function loads params.mat, does the calculations
% and saves the result in result.mat containing the variables c,d,...
load('result.mat', 'c', 'd');
return.c = c;
return.d = d;
% again, it's more than just two return values
So the basic idea is to create variables with the same names as someField
's fieldnames, run a function and create a return
structure using someFunction
's return variable's names as fieldnames.
Is there some way simplify this using some loop e.g. over fieldnames(someField)
?
Or should I 开发者_开发问答 actually use some different approach? Since some further processing is done with someField
and result
I'd like to keep using structs, but maybe a second question would be
Can save
and load
redirect varibale names? I.e. could e.g. the variable a
in params.mat be stored using someField.a
as value instead of having to assign a = someField.a
first?
Why not something like this?
if this is s:
s.a=1
s.b=2
s.c=3
Then this command creates a matfile named "arguments" with variables a, b, c:
save arguments.mat -struct s
And this command loads a matfiles variables into a structure
r = load('arguments.mat')
How about using ASSIGNIN and dynamic fieldnames to loop over the structure fields and create the appropriate variables in the workspace:
function struct2base(s) for f = fieldnames(s)' assignin('base', f{:}, s.(f{:})) end
Have a look at the deal() function.
精彩评论