User`s guide

parfor
11-233
Notably, the assignments to the variables i, t, and u do not affect variables with the
same name in the context of the parfor statement. The rationale is that the body of the
parfor is executed in parallel for all values of i, and there is no deterministic way to
say what the “final” values of these variables are. Thus, parfor is defined to leave these
variables unaffected in the context of the parfor statement. By contrast, the variable
C has a different element set for each value of i, and these assignments do affect the
variable C in the context of the parfor statement.
Another important use of parfor has the following form:
s = 0;
parfor i = 1:n
if p(i) % assume p is a function
s = s + 1;
end
end
The key point of this example is that the conditional adding of 1 to s can be done in any
order. After the parfor statement has finished executing, the value of s depends only on
the number of iterations for which p(i) is true. As long as p(i) depends only upon i,
the value of s is deterministic. This technique generalizes to functions other than plus
(+).
Note that the variable s refers to the variable in the context of the parfor statement.
The general rule is that the only variables in the context of a parfor statement that can
be affected by it are those like s (combined by a suitable function like +) or those like C in
the previous example (set by indexed assignment).
More About
Tips
A parfor-loop runs on the existing parallel pool. If no pool exists, parfor will start
a new parallel pool, unless the automatic starting of pools is disabled in your parallel
preferences. If there is no parallel pool and parfor cannot start one, the loop runs
serially in the client session.
Inside a parfor-loop, the functions labindex and numlabs both always return a
value of 1.
If the AutoAttachFiles property in the cluster profile for the parallel pool is set to
true, MATLAB performs an analysis on a parfor-loop to determine what code files