I have the parallel computing toolbox but I have trouble writing loops in a manner that the toolbox likes. Can someone make a suggestion as to how I can change this code so that I can run parfor on my for loops? When I try to run the loop replacing for with parfor I get the message that I can't do so because of how d is used.
Thanks a lot, Brian
d={};
for r = 1:length(c);
for i = 3:100
d((r-1)*97 + i-2,1) = c(r,1);
d((r-1)*97 + i-2,2) = c(r,2);
d((r-1)*97 + i-2,3) = c(r,i);
d((r-1)*97 + i-2,4) = cellstr(['F' num2str(i)-2]);
end
disp(r);
end

 採用された回答

Walter Roberson
Walter Roberson 2012 年 6 月 6 日

0 投票

When r = 1 and i = 100, then (r-1)*97 + i-2 is 0*97 + 100 - 2 which is 98
When r = 2 and i = 3, then (r-1)*97 + i-2 is 1*97 + 3 - 2 which is 98
Your loops are overwriting locations on different iterations and that is not vectorizable.
length(3:100) is 98, not 97.
I suggest you consider pre-allocating your "d" array as cell(length(c), 98, 4), and index it at (i,r,*) and then at the end of the loop reshape it to ([], 4)

1 件のコメント

Brian
Brian 2012 年 6 月 11 日
Thanks a lot Walter.

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

その他の回答 (1 件)

Brandon Armstrong
Brandon Armstrong 2012 年 6 月 6 日

1 投票

Nested parfor loops I believe are not allowed, but there is away around the indexing problem but putting the inner loop inside a helper function so then your code would look something like
parfor r = 1:length(c);
d = helper_function(r)
end
and helper_function the does the inner loop.

カテゴリ

ヘルプ センター および 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