User`s guide

2 Parallel for-Loops (parfor)
2-38
First consider the reduction function itself. To compare an iteration's result against
another's, the function requires as input the current iteration's result and the known
maximum result from other iterations so far. Each of the two inputs is a vector
containing an iteration's result data and iteration number.
function mc = comparemax(A, B)
% Custom reduction function for 2-element vector input
if A(1) >= B(1) % Compare the two input data values
mc = A; % Return the vector with the larger result
else
mc = B;
end
Inside the loop, each iteration calls the reduction function (comparemax), passing in a
pair of 2-element vectors:
The accumulated maximum and its iteration index (this is the reduction variable,
cummax)
The iteration’s own calculation value and index
If the data value of the current iteration is greater than the maximum in cummmax,
the function returns a vector of the new value and its iteration number. Otherwise, the
function returns the existing maximum and its iteration number.
The code for the loop looks like the following, with each iteration calling the reduction
function comparemax to compare its own data [dat i] to that already accumulated in
cummax.
% First element of cummax is maximum data value
% Second element of cummax is where (iteration) maximum occurs
cummax = [0 0]; % Initialize reduction variable
parfor ii = 1:100
dat = rand(); % Simulate some actual computation
cummax = comparemax(cummax, [dat ii]);
end
disp(cummax);
More About
“Classification of Variables in parfor-Loops” on page 2-23
“Reductions: Cumulative Values Updated by Each Iteration” on page 2-8