Using parfor with a 3d array

I am trying to update a 3d array within a parfor loop. The actual code is too messy to reproduce here but the snippet of code below conveys what I am trying to do (but unable to).
a = zeros(5,5,10):
parfor t = 1:ntimes;
temp = randn(5,5); % In my actual code, this is some meaningful quantity that depends on the loop variable 't'
for k = 1:10;
a(:,:,k) = a(:,:,k) + randn(5,5);
end
end
I get an error saying matlab is unable to classiy the variable 'a'.
Is there a way I can fix this?
Thanks!

回答 (1 件)

Matt J
Matt J 2021 年 2 月 3 日

1 投票

A variable in a parfor loop must belong to one of 5 categories. I cannot tell from your simplified example which category a is supposed to belong to (and neither can parfor), but the table here should help you decide:

6 件のコメント

oceanmod
oceanmod 2021 年 2 月 3 日
Thanks for the reply. I did look at that link but it was not clear why 'a' in my example is not classified.
oceanmod
oceanmod 2021 年 2 月 3 日
I was able to get around this error as follows:
%<same code as before>
for k = 1:10;
temp(:,:,k) = randn(5,5);
end
a = a + temp;
Matt J
Matt J 2021 年 2 月 3 日
編集済み: Matt J 2021 年 2 月 3 日
Thanks for the reply. I did look at that link but it was not clear why 'a' in my example is not classified.
If not, then which class do you think it should belong to?
oceanmod
oceanmod 2021 年 2 月 3 日
I would have thought it should be a reduction variable as it is accumulating values irrespective of the parfor loop order.
I also found this statement in the matlab docs:
"MATLAB Coder does not allow reduction variables to be read anywhere in the parfor-loop except in reduction statements"
I wonder if the above also means a reduction variable cannot appear inside a nested for loop (itself inside a parfor loop).
Matt J
Matt J 2021 年 2 月 3 日
You cannot index or subscript a reduction variable.
oceanmod
oceanmod 2021 年 2 月 3 日
Ah, got it. Thanks again!

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

カテゴリ

ヘルプ センター および File ExchangeLoops and Conditional Statements についてさらに検索

製品

リリース

R2019a

質問済み:

2021 年 2 月 3 日

コメント済み:

2021 年 2 月 3 日

Community Treasure Hunt

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

Start Hunting!

Translated by