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

conditionalconditionally parallelparfor

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.

Best Answer

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