User`s guide

Temporary Variables
2-39
Temporary Variables
A temporary variable is any variable that is the target of a direct, nonindexed
assignment, but is not a reduction variable. In the following parfor-loop, a and d are
temporary variables:
a = 0;
z = 0;
r = rand(1,10);
parfor i = 1:10
a = i; % Variable a is temporary
z = z + i;
if i <= 5
d = 2*a; % Variable d is temporary
end
end
In contrast to the behavior of a for-loop, MATLAB effectively clears any temporary
variables before each iteration of a parfor-loop. To help ensure the independence of
iterations, the values of temporary variables cannot be passed from one iteration of the
loop to another. Therefore, temporary variables must be set inside the body of a parfor-
loop, so that their values are defined separately for each iteration.
MATLAB does not send temporary variables back to the client. A temporary variable in
the context of the parfor statement has no effect on a variable with the same name that
exists outside the loop, again in contrast to ordinary for-loops.
Uninitialized Temporaries
Because temporary variables are cleared at the beginning of every iteration, MATLAB
can detect certain cases in which any iteration through the loop uses the temporary
variable before it is set in that iteration. In this case, MATLAB issues a static error
rather than a run-time error, because there is little point in allowing execution to proceed
if a run-time error is guaranteed to occur. This kind of error often arises because of
confusion between for and parfor, especially regarding the rules of classification of
variables. For example, suppose you write
b = true;
parfor i = 1:n
if b && some_condition(i)
do_something(i);