for (drange)

for-loop over distributed range

Description

example

for loopVar = drange(range); statements; 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 a for-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 use loopVar to index the local part of a codistributed array under the following conditions:

• loop index range is provided in the form range = 1:N

• the array is distributed using the default 1d codistribution scheme

• the array has size N along the distribution dimension

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

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:numlabs)
z = rand(m,1) + i*rand(m,1);
c = sum(abs(z) < 1);
end
k = gplus(c)
p = 4*k/(m*numlabs);
end
p{1}
ans = 3.1501

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 form start:finish or start:increment:finish. The default value of increment is 1.

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

statements must not include functions that perform communication, including the following functions: 