MATLAB Answers

Is it possible to conditionally switch between parallel and non parallel for loops?

104 views (last 30 days)
I would like to be able to set a flag as the input to a function that changes the code from executing a for loop to a parfor loop and vice versa.
It would be handy sometimes so I can debug the contents of the loop (in a standard for) without actually changing the function around it.

Accepted Answer

Edric Ellis
Edric Ellis on 6 Nov 2014
You can do this by setting the optional "number of workers" argument to 0. For example
runInSerial = <...>;
if runInSerial
parforArg = 0;
else
parforArg = Inf;
end
parfor (idx = 1:N, parforArg)
...
end
  4 Comments

Sign in to comment.

More Answers (1)

Sean de Wolski
Sean de Wolski on 6 Nov 2014
I would just write two separate subfunctions one which uses parfor and one that doesn't. Parfor without any workers will be less efficient than a regular for-loop. If the parallel flag is on, call one, else, call the other.
  3 Comments
Matt J
Matt J on 6 Nov 2014
Ah, good to know. And you're right, when I convert my code above to an ordinary script, the parfor version slows down greatly.

Sign in to comment.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!