parfor nested loop ind2sub
조회 수: 5 (최근 30일)
이전 댓글 표시
Alessandro Maria Marco
2023년 1월 17일
댓글: Alessandro Maria Marco
2023년 1월 19일
I have three nested loops and I would like to parallelize all of them using parfor. I know that it is not possible to nest a parfor inside another parfor so first I flatten the nested loop switching from subscripts to linear index. See the example code below:
clear
clc
close all
%% Set up fake data
alpha = 0.36;
delta = 0.06;
sigma = 1.5;
nk = 100;
nkp = 500;
nz = 7;
k_grid = linspace(1e-6,100,nk)';
kp_grid = linspace(1e-6,100,nkp)';
z_grid = linspace(0.5,1.8,nz)';
%% Original problem
disp('Original problem')
tic
Umat = -inf(nkp,nk,nz);
for z_c=1:nz
for k_c=1:nk
for kp_c=1:nkp
z = z_grid(z_c);
k = k_grid(k_c);
kp = kp_grid(kp_c);
cons = z*k^alpha+(1-delta)*k-kp;
if cons>0
Umat(kp_c,k_c,z_c) = cons^(1-sigma)/(1-sigma);
end
end
end
end
toc
%% Flatten the nested loops
disp('Flatten the nested loops')
siz = [nkp,nk,nz];
nn = prod(siz);
tic
Umat1 = -inf(nkp,nk,nz);
for n_c=1:nn % Cannot use parfor here!!
[kp_c,k_c,z_c] = ind2sub(siz,n_c);
z = z_grid(z_c);
k = k_grid(k_c);
kp = kp_grid(kp_c);
cons = z*k^alpha+(1-delta)*k-kp;
if cons>0
Umat1(kp_c,k_c,z_c) = cons^(1-sigma)/(1-sigma);
end
end
toc
err = max(abs(Umat1(:)-Umat(:)))
The flattened loops are slower, as expected since I'm calling another function (ind2sub). However, if I replace the for with parfor I get a mistake and it says that "parfor cannot be used due to the way Umat1 is used". But the iterations are obviously independent, Indeed I have parallelize the above code in Fortran with OpenMP and it works well. Any help/suggestion is greatly appreciated!
댓글 수: 0
채택된 답변
Walter Roberson
2023년 1월 17일
You cannot do that. parfor requires that the indexing of output objects must involve a simple linear transformation of the loop control variable for one index, and constants or : for the other indices.
Use your ind2sub version but assign to Umat1(n_c)
댓글 수: 3
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Matrix Indexing에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!