Parallel nested for-Loop with a compounding variable
2 ビュー (過去 30 日間)
古いコメントを表示
Hi I'm trying to execute a code that contains three for-loops with the innermost loop containing a variable whose value gets compounded at every iteration.
Here is an example:
A = [];
for i = 1:10
for j = 1:10
B = f(i,j);
for k = 1:10
A = A + g(B);
end
end
end
The nested for-loop itself cannot be worked around unfortunately but this is taking too long computation-wise I am trying to incorporate "parfor", the matlab does not allow variable "A". Is there a workaround to this?
Thanks!
0 件のコメント
採用された回答
Kirby Fears
2015 年 10 月 5 日
Each iteration of a parfor loop will be performed in an unpredictable order. Therefore Matlab prevents you from changing the value of a variable in one iteration that will be referenced in another iteration (such as A in your code). This general rule is enforced to ensure coherent calculations are performed.
You should store the values in an array or a cell, then sum the terms after the parfor loop has ended. Here's a simple example that should be adaptable to your problem.
% Initialize an array to store all terms
A=NaN(1,10);
parfor j=1:10,
% Fill each of the j positions independently
A(j)=j;
end,
% Sum A now that parfor is over
A=sum(A);
Hope this helps.
0 件のコメント
その他の回答 (2 件)
Walter Roberson
2015 年 10 月 5 日
If you initialize A as 0 then you can do it with parfor, as A would then be recognized as a "reduction variable". The calculation might internally be done with subtotals that are then totaled, so if your calculation depends critically on the order in which the totals are done then parfor is not appropriate. For example, ((2 + (-2)) + eps(1)) would have a different result than (2 + ((-2) + eps(1)) so if you have carefully programmed your loop to avoid those kinds of round-off problems then you would want to be very careful how you programmed your parfor.
0 件のコメント
参考
カテゴリ
Help Center および File Exchange で Loops and Conditional Statements についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!