How to repeat/continue iteration of a parfor loop without incrementing the loop counter untill condition is satisfied

3 views (last 30 days)
I would like to do a fixed number of simulations, the problem is that while running one, if some conditon is not met, I want to be able not to count the simulaton and redo it.
The logic without a parfor loop is something like this:
runs = 10;
counter = 0;
while counter <= runs
% do something
if condition
continue
end
counter = counter + 1;
end
How to implement the same idea with a parfoor loop?

Accepted Answer

Edric Ellis
Edric Ellis on 8 Apr 2022
It's not entirely clear how your "do something" chooses what to do. I think we need to see a little more detail there. Setting that aside for a moment, here's one possible option:
runs = 10;
parfor ii = 1:10
candidateResult = rand();
while candidateResult < 0.9
% Keep calling 'rand' until we get an acceptable result.
candidateResult = rand();
end
out(ii) = candidateResult;
end
Starting parallel pool (parpool) using the 'local' profile ... Connected to the parallel pool (number of workers: 2).
disp(out)
0.9301 0.9807 0.9604 0.9625 0.9114 0.9821 0.9334 0.9800 0.9460 0.9944
  3 Comments

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!

Translated by