Comparing for-Loops and parfor-Loops

Because parfor-loops are not quite the same as for-loops, there are specific behaviors of each to be aware of. As seen from the example in the topic Create a parfor-Loop, when you assign to an array variable (such as A in that example) inside the loop by indexing with the loop variable, the elements of that array are available in the client workspace after the loop, much the same as with a for-loop.

However, suppose you use a nonindexed variable inside the loop, or a variable whose indexing does not depend on the loop variable i. Try these examples and notice the values of d and i afterward:

clear A
d = 0; i = 0;
for i = 1:4
   d = i*2;
   A(i) = d;
end
A
d
i
A =

     2     4     6     8

d =

     8

i =

     4
clear A
d = 0; i = 0;
parfor i = 1:4
   d = i*2;
   A(i) = d;
end
A
d
i
A =

     2     4     6     8

d =

     0

i =

     0

Although the elements of A come out the same in both of these examples, the value of d does not. In the for-loop above on the left, the iterations execute in sequence, so afterward d has the value it held in the last iteration of the loop. In the parfor-loop on the right, the iterations execute in parallel, not in sequence, so it would be impossible to assign d a definitive value at the end of the loop. This also applies to the loop variable, i. Therefore, parfor-loop behavior is defined so that it does not affect the values d and i outside the loop at all, and their values remain the same before and after the loop. So, a parfor-loop requires that each iteration be independent of the other iterations, and that all code that follows the parfor-loop not depend on the loop iteration sequence.

Related Examples

More About

Was this topic helpful?