フィルターのクリア

Question about parfor nested loop

1 回表示 (過去 30 日間)
haonan He
haonan He 2021 年 1 月 1 日
コメント済み: haonan He 2021 年 1 月 3 日
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 件のコメント
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 日
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 件)

カテゴリ

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