for (drange) - for-loop over distributed range - MATLAB (original) (raw)

Main Content

for-loop over distributed range

Syntax

Description

for [loopVar](#mw%5F7fb8a60b-0844-475c-9603-8e6884908a7a) = drange([range](#mw%5Fe34398ab-92e8-4d4c-9974-c9ca03b0dbd3)); [statements](#mw%5F1c04a465-a626-4499-a84e-fc0eb09634c5); end; executes for-loop iterations in parallel over a distributed range.

MATLABĀ® partitions the range specified by range across the workers in the parallel pool, using contiguous segments of approximately equal length. MATLAB then executes the loop body commands in statements in afor-loop over the specified range of loopVar on each worker.

Each iteration must be independent of the other iterations, such that the iterations can be performed in any order. No communication with other workers is allowed within the loop body.

Each worker can access local portions of codistributed arrays, but cannot access portions of codistributed arrays that are stored on other workers. You can useloopVar to index the local part of a codistributed array under the following conditions:

You can use the break statement to terminate the loop execution.

example

Examples

collapse all

This example shows how to find the rank of magic squares. Access only the local portion of a codistributed array.

spmd r = zeros(1, 40, codistributor()); for n = drange(1:40) r(n) = rank(magic(n)); end end r = gather(r);

This example shows how to perform Monte Carlo approximation of pi.

spmd m = 10000; for p = drange(1:spmdSize) z = rand(m,1) + irand(m,1); c = sum(abs(z) < 1); end k = spmdPlus(c) p = 4k/(m*spmdSize); end p{1}

This example shows how to attempt to compute Fibonacci numbers. This example does not work, because the loop bodies are dependent. The following code produces an error:

spmd f = zeros(1, 50, codistributor()); f(1) = 1; f(2) = 2; for n = drange(3:50) f(n) = f(n-1) + f(n-2) end end

Error detected on workers 2 3 4 5 6.

Caused by: Error using codistributed/subsref (line 40) Error using codistributed/subsref (line 40) Inside a FOR-DRANGE loop, a subscript can only access the local portion of a codistributed array.

Input Arguments

collapse all

Loop variable name, specified as text.

Loop index range, specified as an expression of the formstart:finish or start:increment:finish. The default value of increment is 1.

Version History

Introduced in R2007b