Parallel nested for-Loop with a compounding variable
2 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Jeongseop Lee
el 5 de Oct. de 2015
Respondida: Jeongseop Lee
el 6 de Oct. de 2015
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 comentarios
Respuesta aceptada
Kirby Fears
el 5 de Oct. de 2015
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 comentarios
Más respuestas (2)
Walter Roberson
el 5 de Oct. de 2015
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 comentarios
Ver también
Categorías
Más información sobre Loops and Conditional Statements en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!