2017-07-28 60 views
1

我會(在我的情況,以便保存大文件的預定義version),即像這樣爲matlabs編寫包裝保存功能

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

應該轉向寫與預定義選項MATLAB的save功能的包裝這個

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 

回答

2

因爲變量將不會在功能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  
+0

也許值得指出的,我意識到你可以刪除'v'完全,更新的代碼是可能更高效的存儲器作爲不需要中間變量。 – Wolfie