The while loops works when X/Y is defined in the while loop, but won't run when X/Y is defined in the code above it. I need a while loop that works using the code above it.

조회 수: 3 (최근 30일)
Listed are two types of loops. that are very similar The first one works, the second one doesn't because it runs for eternity. I need a while loop that doesn't need the equation defined in the description. I need it to run based on a defined variable above the while loop. bob in this instance.
%%% First Loop
X=66;
Y=4;
P=3;
%bob=X/Y;
while X/Y > P
Y=Y+1
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%5
%%% Second Loop
X=66;
Y=4;
P=3;
bob=X/Y;
while bob > P
Y=Y+1
end

답변 (2개)

Cris LaPierre
Cris LaPierre 2025년 2월 4일
If you do not update your variable bob inside your while look, you will create a loop that either never runs or runs infinitely.
Said another way, bob > P evaluates to either true or false. If the values of bob and/or P are not changed inside your while loop, your loop is just
while true
Y=Y+1
end
Instead, you need to write your loop this way
X=66;
Y=4;
P=3;
bob=X/Y;
while bob > P
Y=Y+1
bob=X/Y;
end

Voss
Voss 2025년 2월 4일
In the first while loop, X/Y is calculated and compared to P on each iteration. No problem.
In the second while loop, bob is compared to P on each iteration, but neither bob nor P changes as the loop iterates, so the condition bob > P is either always true or always false (in this case always true, so the loop runs forever).
To get the behavior of the second loop to match that of the first, you need to update the value of bob inside the loop:
X=66;
Y=4;
P=3;
bob = X/Y;
while bob > P
Y = Y+1;
bob = X/Y;
end
Y
Y = 22
bob
bob = 3
"I need a while loop that doesn't need the equation defined in the description. I need it to run based on a defined variable above the while loop."
I don't know what your real requirements are, but if you hope to have a loop that runs and then stops at some point, the value of something is going to have to change as the loop iterates. For your purposes, maybe it's convenient to define a function handle F which performs the X/Y calculation.
X=66;
Y=4;
P=3;
F = @(x,y)x/y;
while F(X,Y) > P
Y = Y+1;
end
Y
Y = 22
bob = F(X,Y)
bob = 3

카테고리

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