Clever way to assign multiple fields at once?

烈酒焚心 提交于 2019-12-10 19:06:54

问题


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?


回答1:


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')



回答2:


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



回答3:


Have a look at the deal() function.



来源:https://stackoverflow.com/questions/5091284/clever-way-to-assign-multiple-fields-at-once

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!