The safest approach when creating a parfor
-loop is to assume that iterations
are performed on different MATLAB® workers in the parallel pool,
so there is no sharing of information between iterations. If you have
a for
-loop in which all iterations are completely
independent of each other, this loop is a good candidate for a parfor
-loop.
Basically, if one iteration depends on the results of another iteration,
these iterations are not independent and cannot be evaluated in parallel,
so you cannot easily reprogram the loop into a parfor
-loop.
The
following example produces equivalent results, with a for
-loop
on the left, and a parfor
-loop on the right. Try
typing each in your MATLAB Command Window:
clear A for i = 1:8 A(i) = i; end A 1 2 3 4 5 6 7 8 | clear A parfor i = 1:8 A(i) = i; end A 1 2 3 4 5 6 7 8 |
Notice that each element
of A
is equal to its index. The parfor
-loop
works because each element depends only upon its iteration of the
loop, and upon no other iterations. for
-loops that
merely repeat such independent tasks are ideally suited candidates
for parfor
-loops.
Note
If a parallel pool is not running, |