问题描述
由于遗留函数调用,有时我有时不得不写出丑陋的包装器
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
因此,基本思想是使用与someField
的字段名相同的名称创建变量,运行一个函数,并使用someFunction
的返回变量的名称作为字段名来创建return
结构.
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.
是否有某种方法可以使用某些循环简化此操作,例如在fieldnames(someField)
上?
Is there some way simplify this using some loop e.g. over fieldnames(someField)
?
还是我应该使用一些不同的方法?由于使用someField
和result
完成了一些进一步的处理,所以我想继续使用结构,但也许第二个问题是
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
save
和load
可以重定向变量名称吗? IE.可以例如将someField.a
作为值存储在params.mat中的变量a
而不是必须先分配a = someField.a
吗?
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?
推荐答案
为什么不这样?
如果是s:
s.a=1
s.b=2
s.c=3
然后,此命令创建一个名为"arguments"的matfile,其中包含变量a,b,c:
Then this command creates a matfile named "arguments" with variables a, b, c:
save arguments.mat -struct s
此命令将matfiles变量加载到结构中
And this command loads a matfiles variables into a structure
r = load('arguments.mat')
这篇关于一次分配多个字段的巧妙方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!