running two while loops

조회 수: 17 (최근 30일)
xRobot
xRobot 2019년 11월 24일
답변: Walter Roberson 2019년 11월 25일
Hello,
I am attempting to run two while loops similar to below with check being a value zero or 1:
input(enter guess)
check = check(guess)
while check == 0
do things
input(enter guess)
check = check(guess)
while check == 1
do things
input(enter guess)
check = check(guess)
The problem I am having is that once I am is that once I enter the second loop and check becomes 0 I cannot go back to the above loop I am stuck in the one where check == 1.
Is this an example of a case where parallel while loop tools would be needed like the parallel toolbox.
  댓글 수: 1
Rik
Rik 2019년 11월 24일
Since you rely on user input, it doesn't look to me like this is a parallel process. It looks like you need either two while loops with their own check, or a single loop with two checks in its condition.

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

채택된 답변

Walter Roberson
Walter Roberson 2019년 11월 25일
As a general form you can use something like
need_to_repeat_outer_loop = true;
while need_to_repeat_outer_loop
%some code
need_to_repeat_inner_loop = true;
while need_to_repeat_inner_loop
%some code
if some inner condition
need_to_repeat_inner_loop = false;
end
end
%some code
if some outer condition
need_to_repeat_outer_loop = false;
end
end
Hower, in practice most of the time you would instead write
while true
%some code
while true
%some code
if some inner condition
break; %out of inner loop
end
end
%some code
if some outer condition
break;
end
end
Sometimes you are inside the inner loop and need to signal that the outer loop is to be stopped. For that you can use
while true
%some code
while true
stop_outer = false;
%some code
if some inner condition
stop_outer = true;
break; %out of inner loop
end
end
if stop_outer;
break;
end
%some code
end

추가 답변 (0개)

카테고리

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