indexing within parfor loop

18 ビュー (過去 30 日間)
Adam
Adam 2018 年 2 月 1 日
回答済み: Edric Ellis 2018 年 2 月 2 日
Dear All,
I am having troubles with setting up the following parfor loop.
Basically, I have two variables T and tau and I want to loop over them in parallel.
parfor i = 1:length(tau)*length(T)
k = ceil(i/length(T)); %tau
j = i-(k-1)*length(T); %T
p.T = T(j);
p.tau = tau(k);
fun(p);
end
I get the error message that the problem is with the use of variable p.
Could someone help me how to fix this?
Thank you
  1 件のコメント
Guillaume
Guillaume 2018 年 2 月 1 日
What is the error message?
I would recommend you use numel instead of length. With numel your code will work whether tau and T are matrices or vectors. With length it will break in interesting ways if any of them are matrices.

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

回答 (2 件)

Rik
Rik 2018 年 2 月 1 日
編集済み: Rik 2018 年 2 月 1 日
parfor loops don't like temporary variables, because it will not be able to guarantee which assignment will be the last, so it can't tell which version of p to keep available. You can fix this by either creating a double nested loop (which you can make parfor if you like), or indexing p.
parfor i = 1:numel(tau)*numel(T)
k = ceil(i/numel(T)); %tau
j = i-(k-1)*numel(T); %T
p(i).T = T(j);
p(i).tau = tau(k);
fun(p(i));
end
or
for i_tau = 1:numel(tau)
for i_T=1:numel(T)
p.T = T(i_T);
p.tau = tau(i_tau);
fun(p);
end
end

Edric Ellis
Edric Ellis 2018 年 2 月 2 日
The problem here is that parfor can't tell whether you're updating all fields of the variable p, and therefore it thinks there might be order-dependent stuff going on. The simplest way to fix this is to ensure you completely overwrite p on each iteration of your loop, like this:
parfor i = 1:length(tau)*length(T)
k = ceil(i/length(T)); %tau
j = i-(k-1)*length(T); %T
p = struct('T', T(j), 'tau', tau(k));
fun(p);
end

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

タグ

製品

Community Treasure Hunt

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

Start Hunting!

Translated by