Four Parallel Nested For Loop

3 次查看(过去 30 天)
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