User`s guide

Reduction Variables
2-33
parfor i = 1:n
X = X + d(i);
end
This loop is equivalent to the following, where each d(i) is calculated by a different
iteration:
X = X + d(1) + ... + d(n)
If the loop were a regular for-loop, the variable X in each iteration would get its value
either before entering the loop or from the previous iteration of the loop. However, this
concept does not apply to parfor-loops:
In a parfor-loop, the value of X is never transmitted from client to workers or from
worker to worker. Rather, additions of d(i) are done in each worker, with i ranging over
the subset of 1:n being performed on that worker. The results are then transmitted back
to the client, which adds the workers' partial sums into X. Thus, workers do some of the
additions, and the client does the rest.
Basic Rules for Reduction Variables
The following requirements further define the reduction assignments associated with a
given variable.
Required (static): For any reduction variable, the same reduction function or
operation must be used in all reduction assignments for that variable.
The parfor-loop on the left is not valid because the reduction assignment uses + in one
instance, and [,] in another. The parfor-loop on the right is valid:
Invalid Valid
parfor i = 1:n
if testLevel(k)
A = A + i;
else
A = [A, 4+i];
end
% loop body continued
end
parfor i = 1:n
if testLevel(k)
A = A + i;
else
A = A + i + 5*k;
end
% loop body continued
end