Difference between "||" and "&&" in my loop

6 visualizaciones (últimos 30 días)
Albin Ahlskog
Albin Ahlskog el 21 de Sept. de 2022
Editada: Rik el 22 de Sept. de 2022
I have a while-loop that I want to stop when one of the given criteria is met. My code is as follows:
vxc = 25;
A = [-(c1 + c2)/(m*vxc) (-a*c1 + b*c2)/(m*vxc) - vxc; -(a*c1 - b*c2)/(J*vxc) -(a^2*c1 + b^2*c2)/(J*vxc)];
lambda = eig(A);
delta = 0.01;
while lambda(1) < 0 && lambda(2) < 0
vxc = vxc + delta;
A = [-(c1 + c2)/(m*vxc) (-a*c1 + b*c2)/(m*vxc) - vxc; -(a*c1 - b*c2)/(J*vxc) -(a^2*c1 + b^2*c2)/(J*vxc)];
lambda = eig(A);
if vxc > 100
break
end
end
Where vxc is a critical velocity I'm trying to find. A is a state-matrix for a control theory problem. What I don't understand is why this code stops as I want it to (when either lambda1 or lambda2 is >0) when using the "&&" operator, but using the "||" operator, as I did first, results in vxc approaching infinity as well as both lambda1 and 2 going positive.
Since I want it to stop when one of the values are greater than 0, I feel like the code should read "While lambda1 OR lambda2 is less than 0, do this" but it only works for "While lambda1 AND lambda2 is less than 0, do this".
  1 comentario
Torsten
Torsten el 21 de Sept. de 2022
You want the while loop to exit if lamda1 >= 0 or lambda2 >= 0. So you want the while loop to continue as long as both lambda1 < 0 and lambda2 < 0. Thus the condition as written is correct.
Are you sure both eigenvalues are always real-valued ? This is necessary for your code to work.

Iniciar sesión para comentar.

Respuestas (1)

Rik
Rik el 22 de Sept. de 2022
Editada: Rik el 22 de Sept. de 2022
The or operator means and/or, just like it does in mathematics. You can use the xor function (although no operator or short-circuited version exist).
If you want a more complex stopping condition, you can use while true, and use if blocks with break statements.

Productos


Versión

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by