I need to run a for-loop in batches of 1000. But if 'cc' doesn't reach 100 during the first run, I need to re-run more batches of 1000 until cc reaches 100.
I know that this can be done using a while-loop, however I need to use the parallel toolbox parfor
(quite possibly GPU's as well), and as far as I know it doesn't support while-loops.
Essentially I need to change (reset) the for-loop index inside the if-loop. However, apparently MATLAB's for-loop is designed so that you cannot change its index, in this case, 'i', within the loop. Is there a way around this? There must be a smarter way to do this without using a while loop. Any suggestions?
for i=1:1000
if (abs(i) <= gamma)
% etc..
cc = cc + 1;
end
if cc < 100
i = 1;
end
end
What you can do is run a whole batch, accumulate each pass's independent cc
indicator in an array, and then combine the results outside the parfor
to see if you need to continue. This keeps each pass of the loop independent of the results of other passes, so it can be done in parallel.
n = 1000;
cc = 0;
isDone = 1;
while ~isDone
ccs = zeros(1, n);
parfor i=1:n
if (abs(i) <= gamma)
% ...etc..
ccs(i) = 1;
end
end
cc = cc + sum(ccs);
isDone = cc >= 100;
end
This will waste some work. You can adjust n
to change the batch size and control the tradeoff between wasted work (due to "fragmentation" in the last batch where cc
would have made it to 100 with a smaller batch) vs. the overhead of parallelization.