User`s guide
Reduction Variables
2-35
beginning of each iteration. The parfor on the right is correct, because it does not assign
f inside the loop:
Invalid Valid
f = @(x,k)x * k;
parfor i = 1:n
a = f(a,i);
% loop body continued
f = @times; % Affects f
end
f = @(x,k)x * k;
parfor i = 1:n
a = f(a,i);
% loop body continued
end
Note that the operators && and || are not listed in the table in “Reduction Variables”
on page 2-32. Except for && and ||, all the matrix operations of MATLAB have a
corresponding function f, such that u op v is equivalent to f(u,v). For && and ||, such
a function cannot be written because u&&v and u||v might or might not evaluate v, but
f(u,v) always evaluates v before calling f. This is why && and || are excluded from the
table of allowed reduction assignments for a parfor-loop.
Every reduction assignment has an associated function f. The properties of f that ensure
deterministic behavior of a parfor statement are discussed in the following sections.
Associativity in Reduction Assignments. Concerning the function f as used in the
definition of a reduction variable, the following practice is recommended, but does not
generate an error if not adhered to. Therefore, it is up to you to ensure that your code
meets this recommendation.
Recommended: To get deterministic behavior of parfor-loops, the reduction function
f must be associative.
To be associative, the function f must satisfy the following for all a, b, and c:
f(a,f(b,c)) = f(f(a,b),c)
The classification rules for variables, including reduction variables, are purely syntactic.
They cannot determine whether the f you have supplied is truly associative or not.
Associativity is assumed, but if you violate this, different executions of the loop might
result in different answers.
Note: While the addition of mathematical real numbers is associative, addition of
floating-point numbers is only approximately associative, and different executions of this