Parallel nested for-Loop with a compounding variable

2 ビュー (過去 30 日間)
Jeongseop Lee
Jeongseop Lee 2015 年 10 月 5 日
回答済み: Jeongseop Lee 2015 年 10 月 6 日
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!

採用された回答

Kirby Fears
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.

その他の回答 (2 件)

Walter Roberson
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.

Jeongseop Lee
Jeongseop Lee 2015 年 10 月 6 日
My initial take on this problem based on your answer was to pre-allocate an array, i.e., "Array", to store all the intermediate calculation results under different indices "Array{i,j,k}". The parfor command this did not allow the use of this type of array (it did not recognize the variable type according to the error message). So I had to reduce it to a two-index array instead of the three-index and had a summation along one index take place outside of the nested loop and it works. Thanks.

カテゴリ

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