Choose between for and parfor.

조회 수: 11 (최근 30일)
Martin
Martin 2014년 5월 2일
댓글: Martin 2014년 5월 2일
Hi,
I want to run many simulations. For this I wrote "for" loop. I used parallel computing, using parfor instead; It works well.
Now I would like to have a binary parameter, say P, at the beginning of my program activating or not parallel computing. (if P == 0, use for loop. If P == 1, use parfor loop).
A way to do that is to copy paste the whole loop, write for on the first one, and parfor on the second one. But I would like to avoid that, to keep my program compact and easily modifiable. Do you think it is at all possible?

채택된 답변

Friedrich
Friedrich 2014년 5월 2일
편집: Friedrich 2014년 5월 2일
Hi,
always use parfor as loop type. When no worker pool is open the parfor loop runs as for loop but backwards. But that should not matter. Note: In R2013b there was a new feature introduced which automatically open a new parallel pool when SPMD or PARFOR is executed. You might want to disable that feature in the parallel preference setting of your MATLAB in the case you use R2013b or newer.
Or in the case you dont like that put the whole body of the loop in a function which takes the index as input, e.g.
if run_in_parallel
parfor i=1:n
result(i) = myfun(i, other_args)
end
else
for i=1:n
result(i) = myfun(i, other_args)
end
end
  댓글 수: 1
Martin
Martin 2014년 5월 2일
Ok, thanks. I'll stick with parfor. :)

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Parallel for-Loops (parfor)에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by