How to gather results from a parfor loop?

21 ビュー (過去 30 日間)
Xiaohan Du
Xiaohan Du 2016 年 11 月 23 日
コメント済み: Joss Knight 2016 年 11 月 24 日
Hi all,
I'm new to parallel computing in MATLAB, please forgive my simple question.
I have a test code like this, while I'd like to extract the otpt matrix at 10000th iteration:
inpt = rand(5);
parfor i = 1:10000
otpt = sin(inpt);
end
After running this paralleled code, no error appears, but if I call otpt:
>> otpt
Undefined function or variable 'otpt'.
What if I need the value of otpt?
I did something like this:
inpt = rand(5);
temp = zeros(5);
parfor i = 1:10000
otpt = sin(inpt);
if i == 10000
temp = temp + otpt;
end
end
In this way I can extract the value of otpt at 10000th iteration, but intuitively I do not feel this is correct. So how can I get the value of otpt?
Thank you!
  1 件のコメント
Joss Knight
Joss Knight 2016 年 11 月 24 日
If you need the result from a loop then either you need a result from every iteration, in which case you need to assign into an array that you've initialised before the loop; or your loop is not parallelizable because each iteration depends on the one before - in which case you can't use parfor.

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

採用された回答

Brendan Hamm
Brendan Hamm 2016 年 11 月 23 日
The issue here is that otpt is assigned separately on each of the workers, this makes its classification as a temporary variable. If you would like to access the values afterwards you would want to assign to a reduction or a slicing variable. What you did in the second example is perfectly acceptable, although the example is unrealistic as why use a parfor loop if you only care about the result at a specific iteration?

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeParallel for-Loops (parfor) についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by