Parfor Loops

1 visualización (últimos 30 días)
Brian
Brian el 6 de Jun. de 2012
I have the parallel computing toolbox but I have trouble writing loops in a manner that the toolbox likes. Can someone make a suggestion as to how I can change this code so that I can run parfor on my for loops? When I try to run the loop replacing for with parfor I get the message that I can't do so because of how d is used.
Thanks a lot, Brian
d={};
for r = 1:length(c);
for i = 3:100
d((r-1)*97 + i-2,1) = c(r,1);
d((r-1)*97 + i-2,2) = c(r,2);
d((r-1)*97 + i-2,3) = c(r,i);
d((r-1)*97 + i-2,4) = cellstr(['F' num2str(i)-2]);
end
disp(r);
end

Respuesta aceptada

Walter Roberson
Walter Roberson el 6 de Jun. de 2012
When r = 1 and i = 100, then (r-1)*97 + i-2 is 0*97 + 100 - 2 which is 98
When r = 2 and i = 3, then (r-1)*97 + i-2 is 1*97 + 3 - 2 which is 98
Your loops are overwriting locations on different iterations and that is not vectorizable.
length(3:100) is 98, not 97.
I suggest you consider pre-allocating your "d" array as cell(length(c), 98, 4), and index it at (i,r,*) and then at the end of the loop reshape it to ([], 4)
  1 comentario
Brian
Brian el 11 de Jun. de 2012
Thanks a lot Walter.

Iniciar sesión para comentar.

Más respuestas (1)

Brandon Armstrong
Brandon Armstrong el 6 de Jun. de 2012
Nested parfor loops I believe are not allowed, but there is away around the indexing problem but putting the inner loop inside a helper function so then your code would look something like
parfor r = 1:length(c);
d = helper_function(r)
end
and helper_function the does the inner loop.

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!

Translated by