Hi,
I have a question about the nested parfor loop. Please see the following codes:
clc
clear
parfor i=1:3
for j=1:3
if j<2
B(i,j)=j;
end
end
end
The result of this code should be B=[1;1;1], but the Matlab gives B=[1,1,1;1,1,1;1,1,1]. I have been confused by this problem for a long time and thank you in advance if you have some time to look into the problem.
Haonan

댓글 수: 7

Ive J
Ive J 2021년 1월 1일
편집: Ive J 2021년 1월 1일
Well, you may wanna retry, because this is just impossible!
Walter Roberson
Walter Roberson 2021년 1월 1일
When I test, I get [1;1;1] as you expected.
haonan He
haonan He 2021년 1월 1일
Thanks for your answer. I have tried many times and via different versions of Matlab, including 2016b and 2019a, but the results are the same [1,1,1;1,1,1;1,1,1], which is not expected. I think it is the issue with parallel programming. Please see the following picture for the Matlab result. Thanks very much.
clc
clear
parfor i=1:3
for j=1:3
if j<2
B(i,j)=j;
end
end
end
B
B = 3×1
1 1 1
Ive J
Ive J 2021년 1월 2일
편집: Ive J 2021년 1월 2일
Can you also check this?
B = (0);
parfor ii=1:3
for jj=1:3
if jj<2
B(ii,jj)=jj;
end
end
end
disp(size(B))
haonan He
haonan He 2021년 1월 2일
Thanks Rik. I reran the code on Matlab 2020b and the result was correct, but it was not as expected when I used old versions, e.g, 2016a 2019a. So maybe it is the bug of the old versions.
haonan He
haonan He 2021년 1월 2일
Thanks Ive. I think the problem may be caused by different versions. When I ran your code on old versions, there was a system error "Index beyond matrix dimension", but it is correct on the lateset version 2020b. So maybe it is the bug of the old versions.

댓글을 달려면 로그인하십시오.

 채택된 답변

Matt J
Matt J 2021년 1월 2일
편집: Matt J 2021년 1월 2일

1 개 추천

So maybe it is the bug of the old versions.
Yes, it appears to be version-related. I get the same thing in R2018a. Regardless, it is not good practice to use parfor to loop over sliced variables whose slices, in this case the B(i,:), are not allocated in advance. This cleaner version, for example, does not have the issue:
clc
clear
B=nan(3); %pre-allocate
parfor i=1:3
for j=1:3
if j<2
B(i,j)=j;
end
end
end

댓글 수: 1

haonan He
haonan He 2021년 1월 3일
Thanks Matt. Yes, the code does not generate the error.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Surrogate Optimization에 대해 자세히 알아보기

질문:

2021년 1월 1일

댓글:

2021년 1월 3일

Community Treasure Hunt

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

Start Hunting!

Translated by