for / parfor within if
Mostrar comentarios más antiguos
Is there a way to write something like:
if parallelloop
parfor i=1:n
else
for i=1:n
end
...iterations
end
where parallellop is a boolean.
This code is not accepted by Matlab because the same end for both parfor and for.
A solution I do not accept for many reasons would be:
if parallelloop
parfor i=1:n
...iterations
end
else
for i=1:n
...iterations
end
end
Another solution I would like to have is an #ifdef like approach, but is there any?
Thanks by advance.
2 comentarios
Philippe Lebel
el 21 de Nov. de 2019
Editada: Philippe Lebel
el 21 de Nov. de 2019
what are the reasons why you dont want to put the end statments after the parfor and the for?
Eric
el 22 de Nov. de 2019
Respuestas (1)
Jason Ross
el 21 de Nov. de 2019
1 voto
You can control if a loop is run with parallel workers or not by changing the number of workers. See "Test parfor-Loops by Switching Between Parallel and Serial Execution" in the parfor documentation. Note that even with 0 workers, the parfor is still nondeterministic.
To make your example work, you would set the number of workers to 0 if parallelloop is false.
4 comentarios
Eric
el 22 de Nov. de 2019
Jason Ross
el 22 de Nov. de 2019
You don't need to do that -- parfor will be essentially run as a for without Parallel Computing Toolbox installed. See here.
Eric
el 22 de Nov. de 2019
Jason Ross
el 22 de Nov. de 2019
There have been a lot of changes since then -- the computational time issue might have been a bug, and fixed. The overall point I was getting at was that parfor is interpreted as a for in the absence of Parallel Computing Toolbox being present.
This also does make the implicit assumption that parfor introduces new functionality that would be incompatible with releases that don't know what parfor is, but that's going to be the case with pretty much any arbitrary software package.
Categorías
Más información sobre Parallel for-Loops (parfor) en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!