How to use Matlab `Batch` function

In this example, I will make a simple example about using Matlab “batch” function to run a number of jobs over multiple processors available to your workstation.   To begin with, a few words about “batch” function. This is one of the functions in the Matlab parallel computing toolbox, which is used to run the functions multiple times simultaneously. More information please use “help batch” or “doc batch” .

clc ; clear;

% step 1. create parallel workers. Each worker can be 
% one of your processors. e.g. a dual core computer may 
% have two workers available to Matlab.

c = parcluster() ; 

% step 2. run batch job over, e.g. 4 workers. 
% In this example, I run the script named 'test.m' over
% 4 workers. In the list of batch arguments, 'c' is the 
% object holding the information of parallel workers ;
% 'test' is the name of function without extention ;
% 1 is the number of return output ;
% {1,2,3,4} is a list of input values into 'test.m';

for i = 1: 4 
  j(i) = batch(c, 'test', 1, {1,2,3,4});
end

% step 3. wait until the last worker finishes 

wait(j(end)) ;

exit;

I include the ‘wait’ and ‘exit’ command at the last lines to facilitate the execution of the script in case one wants to run it on the remote server on the background. Assuming the previous codes stay in the file named “batch_test.m”, in this way, simple run the following command in the terminal of the server :

nohup path_to_matlab_binary_executable -nodisplay -nosplash -r "run batch_test" > outfile.txt < /dev/null &

Leave a comment