for

for-loop over distributed range

Syntax

for variable = drange(colonop)
    statement
    ...
    statement
end

Description

The general format is

for variable = drange(colonop)
    statement
    ...
    statement
end

The colonop is an expression of the form start:increment:finish or start:finish. The default value of increment is 1. The colonop is partitioned by codistributed.colon into numlabs contiguous segments of nearly equal length. Each segment becomes the iterator for a conventional for-loop on an individual worker.

The most important property of the loop body is that each iteration must be independent of the other iterations. Logically, the iterations can be done in any order. No communication with other workers is allowed within the loop body. The functions that perform communication are gop, gcat, gplus, codistributor, codistributed, gather, and redistribute.

It is possible to access portions of codistributed arrays that are local to each worker, but it is not possible to access other portions of codistributed arrays.

The break statement can be used to terminate the loop prematurely.

Examples

Find the rank of magic squares. Access only the local portion of a codistributed array.

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

Perform Monte Carlo approximation of pi. Each worker is initialized to a different random number state.

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);

Attempt to compute Fibonacci numbers. This will not work, because the loop bodies are dependent.

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

See Also

| |

Was this topic helpful?