Parallel for loop: Using broadcasting array variable values as indexes

1 回表示 (過去 30 日間)
Barend
Barend 2011 年 11 月 14 日
Good day.
I have recently aquired the parallel computing toolbox to speed up some of our applications. I have run into the following challenge and hope that someone can give me advice on this.
topNodes = [2 3 4 5 6 7];
bottomNodes = [1 2 3 4 5 6];
polarity = [1 1 -1 1 1 1];
nodes = max([topNodes bottomNodes]);
T = zeros(numel(polarity),nodes);
for i = 1:numel(polarity);
if polarity(i) < 0
T(i,bottomNodes(i)) = -1;
T(i,topNodes(i)) = 1;
else
T(i,bottomNodes(i)) = 1;
T(i,topNodes(i)) = -1;
end
end
Now, if I use a parfor loop, it complains. Some assistance will be much appreciated.
Kind regards,
Barend.

採用された回答

Sarah Wait Zaranek
Sarah Wait Zaranek 2011 年 11 月 14 日
For parfor loops, when you index into a sliced variables, restrictions are placed on the first-level variable indices. This allows parfor to easily distribute the right part of the variable to the right workers. One of these first-level indices must be the loop counter variable or the counter variable plus or minus a constant. Every other first-level index must be a constant, a non-loop counter variable, a colon, or an end.
I explain this more in the blog post where you also left this question.
See a possible fix below.
topNodes = [2 3 4 5 6 7];
bottomNodes = [1 2 3 4 5 6];
polarity = [1 1 -1 1 1 1];
nodes = max([topNodes bottomNodes]);
T = zeros(numel(polarity),nodes);
parfor i = 1:numel(polarity);
myData = T(i,:);
if polarity(i) < 0
myData(i,bottomNodes(i)) = -1;
myData(i,topNodes(i)) = 1;
else
myData(i,bottomNodes(i)) = 1;
myData(i,topNodes(i)) = -1;
end
T(i,:) = myData;
end
  3 件のコメント
Sarah Wait Zaranek
Sarah Wait Zaranek 2011 年 11 月 15 日
Yes, there is an overhead to pass the data to and from the workers - so for code that takes seconds to run - there isn't often a speedup. Also, you are correct that vectorization often is a better choice then de-vectorizing and using parfor.
Konrad Malkowski
Konrad Malkowski 2011 年 11 月 17 日
You should also try running the script as a function. In general MATLAB performance is better with functions that with scripts, as scripts are interpreted one line at a time.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeParallel for-Loops (parfor) についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by