为matlabs保存函数编写包装器

为matlabs保存函数编写包装器,matlab,Matlab,我想为matlab的save函数编写一个带有预定义选项的包装器(在我的例子中,预定义的version允许保存大文件),例如 save('parameters.mat', 'some', 'parameters', 'here', '-v.3'); 应该变成这样 save_large('parameters.mat', 'some', 'parameters', 'here'); 其中save\u large是save的包装,其version设置为'-v7.3': function [ ]

我想为matlab的
save
函数编写一个带有预定义选项的包装器(在我的例子中,预定义的
version
允许保存大文件),例如

save('parameters.mat', 'some', 'parameters', 'here', '-v.3');
应该变成这样

save_large('parameters.mat', 'some', 'parameters', 'here');
其中
save\u large
save
的包装,其
version
设置为
'-v7.3'

function [  ] = save_large( filename, varargin )
%varargin to allow for multiple variable storing?

%what to write here to save all variables (declared as chars) stored in
%the workspace where 'save_large' was called with version set to '-v7.3'?

end

由于变量不存在于函数的作用域中,因此必须使用
evalin
“调用者”
工作区获取变量

使用
try
我们还可以确保变量存在于调用者工作区中

要在
.mat
文件中获得正确的变量名,我们可以使用(不推荐的)
eval
函数,或者使用下面的方法将所有变量分配给一个结构,然后使用
保存
中的
-struct
标志

function save_large(filename, varargin)
    % Set up struct for saving
    savestruct = struct();
    for n = 1:numel(varargin)
        % Test if variable exists in caller workspace
        % Do this by trying to assign to struct
        % Use parentheses for creating field equal to string from varargin 
        try savestruct.(varargin{n}) = evalin('caller', varargin{n});
            % Successful assignment to struct, no action needed
        catch
            warning(['Could not find variable: ', varargin{n}]);
        end
    end
    save(filename, '-struct', 'savestruct', '-v7.3');
end

范例

% Create dummy variables and save them
a = magic(3);
b = 'abc';
save_large test.mat a b; 
% Clear workspace to get rid of a and b
clear a b
exist a var % false
exist b var % false
% Load from file
load test.mat
% a and b in workspace
exist a var % true
exist b var % true       

也许值得一提的是,我意识到可以完全删除
v
,更新后的代码可能更节省内存,因为不需要中间变量。