Dynamically Assign Variables in Matlab

前端 未结 2 1978
忘掉有多难
忘掉有多难 2020-12-12 02:07

I have the following function as part of a large codebase, which I inherited:

function = save_function(fpath, a,b,c)
    save(fpath, \'a\', \'b\', \'c\')
end         


        
相关标签:
2条回答
  • 2020-12-12 02:23

    You can use a structure to dynamically define saved variable names.
    This option is documented here.

     function save_function( fpath, varargin )     
     for ii = 1:numel( varargin )
         st.( inputname(ii+1) ) = varargin{ii};
     end
     save( fpath, '-struct', 'st' );
    

    As a rule of thumb, structure with dynamic field names is often better than eval or assignin when it comes to dynamic variable names.

    PS,
    It is best not to use i as variable name in Matlab.

    0 讨论(0)
  • 2020-12-12 02:34

    The trick is to use assignin, which takes a workspace, a variable name, and some data. It then creates, in the specified workspace, a variable with the given name, whose value is the data:

    assignin(workspace, varname, value)
    

    The workspace identifier can be either 'caller' or 'base'. The former creates the variable in the workspace of the function that called the function within which assignin is called; while the latter... I don't know - it doesn't seem to put the variable anywhere I can see.

    The trick is to create a small function to assign variables to the calling workspace, and call this function from within assignin:

    function = save_function(fpath, varargin)
        names = {}
        for i=1:size(varargin,1)
            names{i} = inputname(i+1);  % have to offset by 1 to account for fpath
        end
        create_variables(names, varargin);
        save(fpath, names{:});
    end
    
    function = create_variables(names, vals)
        for i=1:size(names, 1)
            assignin('caller', names{i}, vals{i});
        end
    end
    
    0 讨论(0)
提交回复
热议问题