How to use a parfor loop inside a for loop?

조회 수: 3(최근 30일)
Dominik Mattioli
Dominik Mattioli 2018년 3월 9일
댓글: Dominik Mattioli 2018년 3월 9일
I have a for loop with variables that have dependency. Within that loop I would like to use parfor to perform a costly operation on a variable that is independent across iterations. Below I made an example; say that I want to perform myFun on each entry in the row (in parallel) corresponding to the iteration of the for-loop.
N = 10;
inputVar = [randi(100,N,1),zeros(N,1)];
out = cell(N,2)
for idx = 1:N
inputVars(idx,2) = idx;
parfor jdx = 1:2
out{jdx,kdx} = myFun(inputVars(jdx,kdx))
I'm new to parallel computing. Not sure if this example is a good one. I can provide a better example if asked.

채택된 답변

Walter Roberson
Walter Roberson 2018년 3월 9일
Generally speaking you can do that. However, parfor will have an easier job if you write to an output that is indexed only by the loop index and possibly the : (colon) operator. For example,
temp_input = inputVars(:,kdx);
parfor jdx = 1 : 2
temp_out{jdx} = myfun(temp_input(jdx));
out(:,kdx) = temp_out;
  댓글 수: 3
Dominik Mattioli
Dominik Mattioli 2018년 3월 9일
Good point! Thank you!

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

추가 답변(0개)

Community Treasure Hunt

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

Start Hunting!

Translated by