10

Have a simple question about parfor in MATLAB. I would like to set a flag in my program to change between parfor and regular for loops. Basically, I need this functionality so that some parts of my code can update graphics in a "debug" mode, then when the flag is turned off, use parfor with no graphics updates for speed.

So, I'm looking for something simple that has this functionality:

if (flag)
  for i = 1:n
else
  parfor i = 1:n
end

  % Do loop tasks.

  end

Any help would be greatly appreciated! Thanks!

Mohsen Nosratinia
  • 9,844
  • 1
  • 27
  • 52
Kyle Lynch
  • 235
  • 1
  • 3
  • 6
  • Does reserving a pool size of 1 solve your problem? – Mikhail Apr 13 '12 at 01:50
  • Not exactly because parfor restricts creating any graphical objects, such as plots. Therefore, whenever I desire this output, I have to manually edit the code of the function. – Kyle Lynch Apr 13 '12 at 06:34

3 Answers3

6

No, this is not possible. However, if you can wrap the loop body in a separate function, you can have either a parfor or a for loop call the body, i.e.

if (flag)
   parfor i=1:n
      out(i) = loopBody(i)
   end
else
   for i=1:n
      out(i) = loopBody(i)
   end
end

Alternatively, you can edit the code so that you have either parfor or for in front of your loop, which is what I often end up doing.

Jonas
  • 74,690
  • 10
  • 137
  • 177
  • 2
    If it was April 1, I would comment like "I wish MATLAB had `#define`s! then we could `#define LOOP parfor` or `#define LOOP for` and we wouldn't have this issue!" – Li-aung Yip Apr 13 '12 at 12:08
  • 2
    @Li-aungYip: yes, this would indeed be convenient. `parfor` sucks for debugging. I expect that around R2015a, the problem is fixed, though. – Jonas Apr 13 '12 at 12:13
6

One more option - use the optional argument to PARFOR

if flag
  arg = Inf;
else
  arg = 0;
end
parfor (idx = 1:n, arg)
   ...
end
Edric
  • 23,676
  • 2
  • 38
  • 40
5

When you close the pool by matlabpool close, parfor behaves just like a for and allows all graphics handling. So you just need to close the pool while debugging.

Mohsen Nosratinia
  • 9,844
  • 1
  • 27
  • 52
  • `parfor` does not behave just like `for`, even when there is no pool of workers. The order of the loop iterations is not guaranteed and they can be executed in any order. Typically, just to ensure that you don't rely on them being in the normal order, they are actually executed in *reverse* order. – Sam Roberts May 07 '14 at 20:22
  • 1
    Note that this is no longer quite true - recent versions of MATLAB & PCT *can* automatically open a pool for you, so you might need to use the optional number of workers argument to `parfor` as per my answer. – Edric Apr 16 '15 at 13:07