Four Parallel Nested For Loop

조회 수: 4 (최근 30일)
Ali Raza
Ali Raza 2019년 9월 16일
댓글: Ali Raza 2019년 9월 18일
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...

채택된 답변

Edric Ellis
Edric Ellis 2019년 9월 17일
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))

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by