User`s guide
2 Parallel for-Loops (parfor)
2-16
Limitations of Nested for-Loops
For proper variable classification, the range of a for-loop nested in a parfor must be
defined by constant numbers or variables. In the following example, the code on the left
does not work because the for-loop upper limit is defined by a function call. The code
on the right works around this by defining a broadcast or constant variable outside the
parfor first:
Invalid Valid
A = zeros(100, 200);
parfor i = 1:size(A, 1)
for j = 1:size(A, 2)
A(i, j) = plus(i, j);
end
end
A = zeros(100, 200);
n = size(A, 2);
parfor i = 1:size(A,1)
for j = 1:n
A(i, j) = plus(i, j);
end
end
The index variable for the nested for-loop must never be explicitly assigned other than
in its for statement. When using the nested for-loop variable for indexing the sliced
array, you must use the variable in plain form, not as part of an expression. For example,
the following code on the left does not work, but the code on the right does:
Invalid Valid
A = zeros(4, 11);
parfor i = 1:4
for j = 1:10
A(i, j + 1) = i + j;
end
end
A = zeros(4, 11);
parfor i = 1:4
for j = 2:11
A(i, j) = i + j - 1;
end
end
If you use a nested for-loop to index into a sliced array, you cannot use that array
elsewhere in the parfor-loop. In the following example, the code on the left does not
work because A is sliced and indexed inside the nested for-loop; the code on the right
works because v is assigned to A outside the nested loop:
Invalid Valid
A = zeros(4, 10);
parfor i = 1:4
for j = 1:10
A(i, j) = i + j;
end
A = zeros(4, 10);
parfor i = 1:4
v = zeros(1, 10);
for j = 1:10
v(j) = i + j;