(par)for k=1:N end; select for or parfor loop without code replication
5 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
I like to use for-loop or parfor-loop with function input flag. One way to do that is using if-else with code replication. I wonder is there a cleverer way?
% solution based on code replication
function foo(parflag)
if parflg==true
parfor k=1:3
% processing codes
end
else
for k=1:3
% copy of processing codes
end
end
end
%% wondering how to make this idea work?
function hoo(parflag)
if parflag==true
forString = str2func('parfor')
else
forString = str2func('for')
end
forString k=1:3
% processing codes
end
end
0 comentarios
Respuesta aceptada
Matt J
el 23 de Ag. de 2023
Editada: Matt J
el 23 de Ag. de 2023
You can avoid replicating the loop code as follows.
numWorkers={}; % or whatever
if ~parflag
numWorkers={0};
end
parfor (k=1:3, numWorkers{:})
% processing codes
end
Be mindful, though, that parfor loops have stronger requirements on the code structure, and you would be limiting yourself to that, even when running serially.
13 comentarios
Más respuestas (0)
Ver también
Categorías
Más información sobre Parallel for-Loops (parfor) 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!