Main Content

for (drange)

for-loop over distributed range

Description

example

forloopVar= drange(range);statements; end;executesfor-loop iterations in parallel over a distributed range.

MATLAB®partitions the range specified byrangeacross the workers in the parallel pool, using contiguous segments of approximately equal length. MATLAB then executes the loop body commands instatementsin afor-loop over the specified range ofloopVaron 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 useloopVarto index the local part of a codistributed array under the following conditions:

  • loop indexrangeis provided in the formrange = 1:N

  • the array is distributed using the default1dcodistribution scheme

  • the array has sizeNalong the distribution dimension

You can use thebreak执行语句终止循环。

Examples

collapse all

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

spmdr = zeros(1, 40, codistributor());forn = drange(1:40) r(n) = rank(magic(n));endendr = gather(r);

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

spmdm = 10000;forp = drange(1:numlabs) z = rand(m,1) + i*rand(m,1); c = sum(abs(z) < 1);endk = gplus(c) p = 4*k/(m*numlabs);endp{1}
ans = 3.1501

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

spmdf = zeros(1, 50, codistributor()); f(1) = 1; f(2) = 2;forn = drange(3:50) f(n) = f(n-1) + f(n-2)endend
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:finishorstart:increment:finish. The default value of increment is1.

Loop body, specified as text. The series of MATLAB commands to execute in thefor-loop.

statementsmust not include functions that perform communication, including the following functions:

版本历史

Introduced in R2007b

See Also

||