Can a Matlab PARFOR loop be programmatically switched on/off?

江枫思渺然 提交于 2019-12-10 12:56:30

问题


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!


回答1:


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.




回答2:


One more option - use the optional argument to PARFOR

if flag
  arg = Inf;
else
  arg = 0;
end
parfor (idx = 1:n, arg)
   ...
end



回答3:


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.



来源:https://stackoverflow.com/questions/10133340/can-a-matlab-parfor-loop-be-programmatically-switched-on-off

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!