while true vs. for i= 1:Inf

조회 수: 1 (최근 30일)
Michael Loder
Michael Loder 2012년 12월 13일
댓글: Walter Roberson 2022년 12월 28일
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?

답변 (3개)

per isakson
per isakson 2012년 12월 13일
The for-loop provide the loop-variable, ii. Why, is that interesting?

James Tursa
James Tursa 2012년 12월 13일
편집: James Tursa 2012년 12월 13일
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)
  댓글 수: 2
Matt Fig
Matt Fig 2012년 12월 14일
Warning: Warning: FOR loop index is too large. Truncating to 281474976710655
bym
bym 2012년 12월 14일
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

댓글을 달려면 로그인하십시오.


Azzi Abdelmalek
Azzi Abdelmalek 2012년 12월 13일
k=0;
while rand<0.8
k=k+1;
end
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
  댓글 수: 2
michal.markun
michal.markun 2022년 12월 28일
Why not? Even if slightly longer code...
for k=1:Inf,
if rand>=0.8,
break,
end;
end;
Walter Roberson
Walter Roberson 2022년 12월 28일
Because it might take more than 281474976710655 iterations which is the limit for 1:inf loops.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by