Problem in using 'break' and 'while'
Ältere Kommentare anzeigen
I have problem in the while loop below. Looks like the break doesn't work, because sometimes R<=0.3 and s becomes one or bigger. What I need is that when R<=0.3 the loop should stop, and when R>0.3 a new x should be generated.
x= rand(); a=0; s=0;
while x>0.1
R=rand();
if R<= 0.3
a=a+1;
break
else
s=s+1;
x=rand();
end
end
Thanks,
Antworten (1)
This will prove to you that the break statement does work:
x= rand();
a=0;
s=0;
while 1 % Infinite loop? If break doesn't work then yes!
R=rand();
if R<= 0.3
a=a+1;
break % The only way out of the loop...
else
s=s+1;
x=rand();
end
end
When I run this, I always get a=1 (as expected), and s ranges form 0 to 6 on average. But the break statement is clearly working...
4 Kommentare
Jalali
am 5 Okt. 2012
1 always evaluates to "true" when used as a conditional.
if 1,disp('Inside IF'),end % Change 1 to 0 and re-try!
Thus the only way out of the loop is with the break statement. I set it up that way so that we know for sure the break statement worked.
Image Analyst
am 5 Okt. 2012
You could also use true instead of 1 - maybe using true would have made it more understandable???
Matt Fig
am 5 Okt. 2012
true
;-)
Kategorien
Mehr zu Loops and Conditional Statements finden Sie in Hilfe-Center und File Exchange
Produkte
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!