Is an infinite for loop infinite?
Afficher commentaires plus anciens
This is a rather theoretical Question: If i have a for loop i=1:Inf, will the loop run forever or stop, when the loop index exceeds realmax? The loop index still grows after reaching 2^53, so matlab seems to have some internal measures to counter precision loss in this case...
1 commentaire
Jonathan Vorndamme
le 3 Juil 2020
Réponse acceptée
Plus de réponses (2)
Walter Roberson
le 3 Juil 2020
No, if you use
for i=1:inf
then MATLAB will stop after 9223372036854775806 iterations. That number is 2^63 - 2
On my system, an empty for loop got through roughly 1.5 * 2^36 iterations in a minute, so the loop would last only about 153 years.
1 commentaire
Jonathan Vorndamme
le 3 Juil 2020
The for-loop will run for int64(inf) iterations. If you want an actual unending loop, consider using while true.
5 commentaires
Walter Roberson
le 3 Juil 2020
Not actually correct, Rik.
for K = 1 : inf; end
Now after a short period, control-C to terminate the loop. You will then receive the message
Warning: Too many FOR loop iterations. Stopping after 9223372036854775806 iterations.
I filed a bug report a few releases ago that the message should be when the loop starts rather than when it terminates.
Rik
le 3 Juil 2020
Thanks for the correction. I'll probably delete this answer and post my suggestion as a comment on yours.
Jonathan Vorndamme
le 3 Juil 2020
Jonathan Vorndamme
le 3 Juil 2020
John D'Errico
le 3 Juil 2020
The timing of the warning message is sort of deep in MATLAB.
for ind = 1:realmax
drawnow
end
Warning: Too many FOR loop iterations. Stopping after 9223372036854775806 iterations.
Inside the loop, I forced MATLAB to update figure windows, process callbacks, etc. When I did that, now the warning appears immediately. Essentially, the warning always gets issued immediately. However, the warning only shows up when MATLAB takes a chance to take a breath. Drawnow forced that to happen, so the warning pops out.
Catégories
En savoir plus sur Loops and Conditional Statements dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!