Use Nested Functions and Variables in parfor
-Loops
Nested Functions
The body of a parfor
-loop cannot make reference to a nested function. However, it can call a nested function by means of a function handle.
Nested Loops
The body of a parfor
-loop cannot contain another parfor
-loop. But it can call a function that contains another parfor
-loop.
However, because a worker cannot open a parallel pool, a worker cannot run the inner nested parfor
-loop in parallel. This means that only one level of nested parfor
-loops can run in parallel. If the outer loop runs in parallel on a parallel pool, the inner loop runs serially on each worker. If the outer loop runs serially in the client (e.g., parfor
specifying zero workers), the function that contains the inner loop can run the inner loop in parallel on workers in a pool.
The body of a parfor
-loop can contain for
-loops. You can use the inner loop variable for indexing the sliced array, but only if you use the variable in plain form, not part of an expression. For example:
A = zeros(4,5); parfor j = 1:4 for k = 1:5 A(j,k) = j + k; end end A
Further nesting of for
-loops with a parfor
is also allowed.
Limitations of Nested for-Loops
For proper