Parallelizing loops in MATLAB – Nested parfor


parallelizing a loop in MATLAB could be as easy as changing:

for idx=1:N
  some statements
end % of idx loop

to

parfor idx=1:N

  some statements

end %of idx loop

However, you can not have nested parfor in matlab. So, the following will NOT work:

parfor idx1=1:N
  parfor idx2=1:M

    some statements using idx1 and idx2

  end % of idx2 loop
end % of idx1 loop

An easy work around is to combine these two loops into one loop and then get the idx1 and idx2 within the loop as follow:

parfor masterIDX=1: (N*M)
  [idx2,idx1]=ind2sub([M,N],masterIDX);

  some statements using idx1 and idx2

end % of masterIdx loop

This can be used to combine as many nested loops as needed:

parfor masterIDX=1: (N1*N2*...*Nn)
  [idxn,..,idx2,idx1]=ind2sub([Nn,..,N2,N1],masterIDX);

  some statements using idx1, idx2, ..., idxn

end % of masterIdx loop

Of course, all these nested loop needs to be independent of each other, that is one should not depend on the results of the others, to parallelize them like this.

Advertisements
This entry was posted in Program, Script, Tech Tips and tagged , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s