如何在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屋!