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.
4 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
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
0 comentarios
Respuestas (2)
Cris LaPierre
el 4 de Feb. de 2025
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
0 comentarios
Voss
el 4 de Feb. de 2025
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
bob
"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
bob = F(X,Y)
0 comentarios
Ver también
Categorías
Más información sobre Loops and Conditional Statements en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!