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

조회 수: 8 (최근 30일)
Albin Ahlskog
Albin Ahlskog 2022년 9월 21일
편집: Rik 2022년 9월 22일
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
Torsten
Torsten 2022년 9월 21일
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.

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

답변 (1개)

Rik
Rik 2022년 9월 22일
편집: Rik 2022년 9월 22일
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.

카테고리

Help CenterFile Exchange에서 String에 대해 자세히 알아보기

제품


릴리스

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by