MATLAB Answers

Michael Loder

while true vs. for i= 1:Inf

Asked by Michael Loder
on 13 Dec 2012

So I was recently posed with the question, what is the difference between a while true loop and a for i = 1:Inf loop. I have done quite a bit of research, but I cannot seem to come up with an answer. Do you know?



No products are associated with this question.

3 Answers

Answer by per isakson
on 13 Dec 2012

The for-loop provide the loop-variable, ii. Why, is that interesting?


Answer by James Tursa
on 13 Dec 2012
Edited by James Tursa
on 13 Dec 2012

In addition to what Per Isakson has written, I would add that the loop variable, after a certain point, will lose precision and become ill-defined. I think MATLAB will try to gracefully provide a value for ii, but after a point the successive ii's will be equal to each other until the background rounding scheme clocks it over into the next representable value. (As I recall, there was a previous similar thread some time ago that explored this topic)


Matt Fig
on 14 Dec 2012
Warning: Warning: FOR loop index is too large. Truncating to 281474976710655
on 14 Dec 2012

There is also a MISRA-C rule regarding a while true vs a for loop in C, but I do not know if that extends to Matlab

Answer by Azzi Abdelmalek
on 13 Dec 2012
while rand<0.8

The while loop will run until a condition rand < 0.8 is false, we don't know when it occurs, because rand is a random number. In this case we can't use a for loop


Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi test

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

MATLAB Academy

New to MATLAB?

Learn MATLAB today!