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?

조회 수: 7 (최근 30일)
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
Rik
Rik 2018년 7월 2일
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
RACHNA DANDWANI 2018년 7월 3일
Thank you. I tried your solution and realised my approach needed correction. My code works fine now.

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

채택된 답변

Adam Danz
Adam Danz 2018년 7월 3일
편집: Adam Danz 2018년 7월 3일
Statements a and b are necessary in my code to change the condition 1. Hence I want the entire loop to run such that each iteration of the for loop changes the variables in a way that renders condition1 false. As soon as that happens, I'd like to come out of the for loop.
The goal here is still not entirely clear but based on your comment above, as @Rik Wisselink mentioned, it seems like you want a conditional statement in place of the while loop and a while loop in place of the for loop. Does this do what want it to?
t=0:0.5:100;
lengthT = length(t);
i = 0;
while i <= lengthT
if condition1
disp('Task accomplished')
statement a
statement b
i = i+1;
else
break %When condition1 becomes false, here we enter the while-loop
end
end
% We end up here if condition1 becomes false -OR- when i>lengthT
statement c

추가 답변 (1개)

Alpha Bravo
Alpha Bravo 2018년 7월 2일
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
Dennis
Dennis 2018년 7월 3일
편집: Dennis 2018년 7월 3일
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
RACHNA DANDWANI 2018년 7월 3일
Thank you. The problem is solved by what Rik Wisselink and Adam Danz suggested. Your help is appreciated

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

카테고리

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