restarting a while loop without finishing the remaining code.

I am trying to make a while loop that will restart the program when the criteria is met. Currently it will restart the program but only after the entire program has run and i want it to restart before finishing.

 채택된 답변

Marta Salas
Marta Salas 2014년 3월 8일
편집: Marta Salas 2014년 3월 8일
continue command restart the while loop. When condition holds the code after the if will not be run.
while(1)
%%your code
if(condition)
continue;
end
%%your code
end

댓글 수: 6

I tried it and it did not do what was necessary, I have edited my original question because I was not clear enough.
My program will restart the while loop but it finishes running the program first- which i do not want it to do.
Other options?
If the condition is true, the code after the if should not be execute ever. Are you sure your condition becomes true?
I think I may be messing something up. If you would like to look I have attached it, the code is not as clean as my usual stuff but you can still probably follow it, if not thanks for the help this far.
I had to submit it for my class but i want to figure out why i am messing this up.
where is the attached code?
sorry i never actually clicked attach file

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

추가 답변 (1개)

Marta Salas
Marta Salas 2014년 3월 9일
편집: Marta Salas 2014년 3월 9일
Just in case you need the solution to your problem. You wanna break the while loop when all the values are not positive, so, you used 2 nested for:
for i=1:1:r
for j=1:1:c
if MS(i,j)<=0
fprintf('Please enter a new matrix with all positive values.\n')
z=1;
continue;
end
end
end
The "continue" statement passes control to the next iteration of the for loop or while loop in which it appears, skipping any remaining statements in the body of the loop. In this code you have nested for and while loops, it skips iteration on this for loop "for j=1:1:c".
For your problem, I would propose a solution like this one:
% look for values <=0 and [r,c] are the indexes where these values appear
% if there is no negative values, r and c are empty arrays
[r,c]= find(MS<=0);
if(~isempty(r) & ~isempty(c))
fprintf('Please enter a new matrix with all positive values.\n')
z=1;
continue;
end

카테고리

도움말 센터File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

제품

태그

질문:

2014년 3월 8일

편집:

2014년 3월 9일

Community Treasure Hunt

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

Start Hunting!

Translated by