How to repeat/continue iteration of a parfor loop without incrementing the loop counter untill condition is satisfied
8 次查看(过去 30 天)
显示 更早的评论
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?
0 个评论
采纳的回答
Edric Ellis
2022-4-8
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
disp(out)
3 个评论
Edric Ellis
2022-4-8
Really my uncertainty is around how you're selecting the things to do in "do something". In a typical parfor loop, your "do something" would depend on the loop index ii. However, if "do something" depends only on ii, then you'll always get the same answer, and never satisfy your condition. In the example I show, I'm using rand to avoid the problem because it is not deterministic. Here's some a silly non-working example that shows how things could go wrong if you have a completely deterministic "do something".
runs = 10;
parfor ii = 1:10
candidateResult = ii + 3;
while candidateResult < 42 % This will never complete
candidateResult = ii + 3;
end
out(ii) = candidateResult;
end
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Parallel for-Loops (parfor) 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!