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

8 visualizzazioni (ultimi 30 giorni)
Albin Ahlskog
Albin Ahlskog il 21 Set 2022
Modificato: Rik il 22 Set 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 Commento
Torsten
Torsten il 21 Set 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.

Accedi per commentare.

Risposte (1)

Rik
Rik il 22 Set 2022
Modificato: Rik il 22 Set 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.

Prodotti


Release

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by