MATLAB: Four Parallel Nested For Loop

parallel computingparallel for loopparfor

How can I use parfor loop for that kind of four nested loop,
for a = [1:12]
for b = [1:51]
for c = [1:12]
for d = [1:51]
function(a,b,c,d) = x(a,b,c,d)*y;
end
end
end
end
Thanks in Advance…

Best Answer

It's generally best to parallelise the outermost loop. However, you need to balance that against ensuring the parfor loop has sufficient iterations to keep all the workers busy. One trick that you can use is to "linearize" the indexing - i.e. convert to a single loop over the entire range, and get back to the individual coordinates using ind2sub. Here's a short example:
M = 3;
N = 4;
P = 5;
Q = 6;
% Approach 1: parallelize only the outer loop
out1 = zeros(M, N, P, Q);
parfor ii = 1:M
for jj = 1:N
for kk = 1:P
for ll = 1:Q
out1(ii,jj,kk,ll) = ii * 1000 + jj * 100 + kk * 10 + ll;
end
end
end
end
% Approach 2: convert to linear indexing
out2 = zeros(M, N, P, Q);
parfor idx = 1:(M*N*P*Q)
% IND2SUB converts from a "linear" index into individual
% subscripts
[ii,jj,kk,ll] = ind2sub([M,N,P,Q], idx);
out2(idx) = ii * 1000 + jj * 100 + kk * 10 + ll;
end
% Check
assert(isequal(out1, out2))