Four Parallel Nested For Loop

2 ビュー (過去 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))
  1 件のコメント
Ali Raza
Ali Raza 2019 年 9 月 18 日
Thanks

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by