Main Content

Use parfor-Loops for Reduction Assignments

These two examples show parfor-loops using reduction assignments. A reduction is an accumulation across iterations of a loop. The example on the left uses x to accumulate a sum across 10 iterations of the loop. The example on the right generates a concatenated array, 1:10. In both of these examples, the execution order of the iterations on the workers does not matter: while the workers calculate individual results for each iteration, the client properly accumulates and assembles the final loop result.

x = 0;
parfor i = 1:10
    x = x + i;
end
x
x =

    55
x2 = [];
n = 10;
parfor i = 1:n
    x2 = [x2, i];
end
x2
x2 =

     1     2     3     4     5     6     7     8     9    10

If the loop iterations operate in a nondeterministic sequence, you might expect the concatenation sequence in the example on the right to be nonconsecutive. However, MATLAB® recognizes the concatenation operation and yields deterministic results.

The next example, which attempts to compute Fibonacci numbers, is not a valid parfor-loop because the value of an element of f in one iteration depends on the values of other elements of f calculated in other iterations.

f = zeros(1,50);
f(1) = 1;
f(2) = 2;
parfor n = 3:50
    f(n) = f(n-1) + f(n-2);
end

When you are finished with your loop examples, clear your workspace and delete your parallel pool of workers:

clear
delete(gcp)

Related Topics