I have a while loop inside a for loop. If the condition of the while loop is not satisfied, I want to jump directly to the end of the for loop. Could anyone please help?
Mostra commenti meno recenti
t=0:0.5:100;
for i=1:length(t)
while(condition1)
display('Task accomplished')
end %while loop ends here
statement a
statement b
end %for loop ends here
statement c %If condition 1 fails, this is where I want to jump to (directly out of the for loop, irrespective of the value of t)
3 Commenti
The while loop will repeat indefinitely until condition1 becomes false unless you have a conditional 'break' embedded within the while loop. In other words, your statement a and statement b will only be executed when condition1 becomes false. The goal here is a bit unclear to me.
Rik
il 2 Lug 2018
I agree with Adam. It seems like you want if instead of while, and that the command you're looking for is break.
RACHNA DANDWANI
il 3 Lug 2018
Risposta accettata
Più risposte (1)
Alpha Bravo
il 2 Lug 2018
This is one way to do it.
t=0:0.5:100;
for i=1:length(t)
while(condition1)
display('Task accomplished')
code % do something here to change condition1
end %while loop ends here
if (~condition1)
break
end
statement a
statement b
end %for loop ends here
statement c
4 Commenti
This code has the same problem as the original code being discussed in the comment section to the question. In your version of the code, statement a and statement b will never be executed. As long as condition1 is true the code will never escape the while loop. As soon as condition1 becomes false, it exits the while-loop and because of your conditional break, it will always skip the rest of the for-loop.
RACHNA DANDWANI
il 3 Lug 2018
If you need statement a/b to change condition1 you need to do that inside your while loop.
I actually just wanted to type a small example, however i noticed that if you want to exit your for loop the moment condition 1 gets false and you change condition 1 inside your while loop, the for loop will only be iterated once.
Maybe you can clarify what you are trying to do?
RACHNA DANDWANI
il 3 Lug 2018
Categorie
Scopri di più su Loops and Conditional Statements in Centro assistenza e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!