MATLAB Language Multithreading Using parfor to parallelize a loop


Example

You can use parfor to execute the iterations of a loop in parallel:

Example:

poolobj = parpool(2);       % Open a parallel pool with 2 workers 

s = 0;                      % Performing some parallel Computations
parfor i=0:9
    s = s + 1;
end
disp(s)                     % Outputs '10'

delete(poolobj);            % Close the parallel pool

Note: parfor cannot be nested directly. For parfor nesting use a function in fisrt parfor and add second parfor in that function.

Example:

parfor i = 1:n
[op] = fun_name(ip);
end

function [op] = fun_name(ip)
parfor j = 1:length(ip)
% Some Computation
end