This is machine translation

Mouseover text to see original. Click the button below to return to the English version of the page.

Note: This page has been translated by MathWorks. Click here to see
To view all translated materials including this page, select Country from the country navigator on the bottom of this page.

Translate This Page

MathWorks Machine Translation

The automated translation of this page is provided by a general purpose third party translator tool.

MathWorks does not warrant, and disclaims all liability for, the accuracy, suitability, or fitness for purpose of the translation.

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.