Monday, November 17, 2014

MATLAB: use 'save' in 'parfor' loop

In the Parallel Computing Toolbox of MATLAB, parfor plays a significant role to speed up the MATLAB simulation. It is not uncommon that we need to save something at the end of each loop. While you want to use save, MATLB will kindly remind you that "SAVE cannot be called in a PARFOR loop". To fix this issue, the save command should be used in a function instead of being called directly in your parfor loop. For example,
parfor m =1:100
 (your code here...)
 save_parfor(mat_file, var1, var2)
end

 The mat_file is where the variable data will be saved, and var1, var2 are simply the variables themselves (not their names). Inside the save_parfor function, the save command is called. The complete save_parfor function is given below.
 
function save_parfor(name_mat, varargin)
% save_parfor 
%
%   Inputs: name_mat: where the .mat will be saved, absolute path is
%                     recommended.
%           varargin: the variables will be saved, don't pass on the names of
%                     the variables, i.e, strings.
%
%   Outputs: 
%
%
% EXAMPLE
%
%
% NOTES
% Wenbin, 11-Nov-2014
% History:
% Ver. 11-Nov-2014  1st ed.

num_vars =nargin-1;
name_input =cell(1, num_vars);
for m = 1:num_vars
   name_input{m} =inputname(1+m);
   eval([name_input{m} '=varargin{m};']);
end

save(name_mat, name_input{:});

No comments:

Post a Comment