How can I move variables into and out of a structure akin to LOAD and SAVE in MATLAB?

╄→гoц情女王★ 提交于 2019-11-29 09:56:25

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

A couple notes:

  • 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.

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