Parfor Loops

1 次查看(过去 30 天)
Brian
Brian 2012-6-6
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
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 个)

Brandon Armstrong
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.

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by