Four Parallel Nested For Loop
2 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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...
0 commentaires
Réponse acceptée
Edric Ellis
le 17 Sep 2019
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))
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!