Dynamically Assign Variables in Matlab

前端 未结 2 2006
忘掉有多难
忘掉有多难 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.

提交回复
热议问题