如何在 MATLAB 中将变量移入和移出类似于 LOAD 和 SAVE 的结构? [英] How can I move variables into and out of a structure akin to LOAD and SAVE in MATLAB?
问题描述
有没有一种快速的方法(即一行)将变量集合转储到一个结构中,使用变量名称作为结构字段?加载"功能基本上是这样做的,但保存和加载到临时文件看起来很难看.
Is there a quick way (i.e. one line) to dump a collection of variables "in" a structure, using the variable names as the structure fields? The "load" function basically does this but saving and loading to a temporary file seems ugly.
例如:
clear
a = 'adsf'
b = rand(10);
x = var2struct(a,b)
x.a
x.b
或者更好:
x = var2struct(['a';'b'])
另外,反过来呢(即将字段值作为以字段命名的变量转储到当前范围)?:
Also, what about the reverse (i.e. dumping the field values to the current scope as variables named after the fields)?:
clear
x.a='asdf'
x.b=rand(10);
dumpstruct(x)
a
b
另外,这里有一个相关的新闻组线程.
Also, here's a related newsgroup thread.
推荐答案
除了使用 加载 和 保存,我知道没有内置函数可以做到这一点.但是,您可以制作自己的函数,如下所示:
Aside from using LOAD and SAVE, there is no built-in function that I know of to do this. However, you could just make your own functions, like so:
function s = var2struct(varargin)
names = arrayfun(@inputname,1:nargin,'UniformOutput',false);
s = cell2struct(varargin,names,2);
end
function struct2var(s)
cellfun(@(n,v) assignin('base',n,v),fieldnames(s),struct2cell(s));
end
从基础工作区工作,您可以像这样使用这些功能:
Working from the base workspace, you can use these functions like so:
a = 'adsf'
b = rand(10);
x = var2struct(a,b);
clear a b
struct2var(x);
几个注意事项:
如果您希望将
var2struct
的参数指定为变量名而不是变量本身,这里有一个替代函数:
If you would rather specify the arguments to
var2struct
as the variable names instead of the variables themselves, here is an alternative function:
function s = var2struct(varargin)
values = cellfun(@(n) evalin('base',n),varargin,'UniformOutput',false);
s = cell2struct(values,varargin,2);
end
您将在基础工作区中使用它,如下所示:
And you would use this from the base workspace as follows:
x = var2struct('a','b');
很遗憾,您只能使用此版本的函数从基础工作区而不是函数的工作区获取变量.
Unfortunately, you can only use this version of the function to get variables from the base workspace, not the workspace of a function.
对上述 struct2var
函数的一个警告是,它总是在基础工作区中创建变量,而不是调用 struct2var
的函数的工作区.要在除基础之外的工作区中创建变量,您必须在该工作区中使用这一行,而不是调用 struct2var
:
One caveat with the struct2var
function above is that it will always create the variables in the base workspace, not the workspace of the function calling struct2var
. To create variables in a workspace other than the base, you would have to use this line in that workspace instead of calling struct2var
:
cellfun(@(n,v) assignin('caller',n,v),fieldnames(x),struct2cell(x));
这篇关于如何在 MATLAB 中将变量移入和移出类似于 LOAD 和 SAVE 的结构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!