【问题标题】:write wrapper for matlabs save function为matlab保存功能编写包装器
【发布时间】:2017-07-29 00:33:13
【问题描述】:

我会为 matlab 的 save 函数编写一个带有预定义选项的包装器(在我的情况下预定义 version 以允许保存大文件),即类似这样的东西

save('parameters.mat', 'some', 'parameters', 'here', '-v.3');

应该变成这个

save_large('parameters.mat', 'some', 'parameters', 'here');

其中save_largesave 的包装器,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

【问题讨论】:

    标签: matlab


    【解决方案1】:

    因为变量不会存在于函数save_large 的范围内,所以您必须使用evalin"caller" 工作区获取变量。

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

    要在 .mat 文件中获取正确的变量名称,我们可以使用(不鼓励的)eval 函数,或者下面将所有变量分配给结构的方法,然后使用 -struct标记save

    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,更新后的代码可能会更节省内存,因为不需要中间变量。
    猜你喜欢
    • 1970-01-01
    • 2013-07-04
    • 1970-01-01
    • 2016-08-15
    • 1970-01-01
    • 1970-01-01
    • 2021-10-05
    • 1970-01-01
    相关资源
    最近更新 更多