How to detect negative number in Switch and case statement

조회 수: 8 (최근 30일)
Telema Harry
Telema Harry 2021년 8월 10일
댓글: Telema Harry 2021년 8월 10일
I want to implement some control actions based on the sign of the error and Uz.
when error = -1, Uz = -1.
The output is 'other value' instead of 'Object losing altitude'.
Please how can I correct it.
Thank you for the help.
error = -1;
Uz = -1;
switch error
case error > 0 && Uz > 0
disp('Controller should not take any action')
case error > 0 && Uz < 0
disp('Open the control valve and supply more lifting gas')
case error < 0 && Uz < 0
disp('Object losing altitude')
otherwise
disp('other value')
end

채택된 답변

Scott MacKenzie
Scott MacKenzie 2021년 8월 10일
Look carefully. Because you are switching on error, your first case expression reduces to
error == (error < 0 && Uz > 0)
which is false. In fact, all your case expressions are false so the otherwise statement always executes.
The fix: Just use an if-else arrangement:
error = -1;
Uz = -1;
if error > 0 && Uz > 0
disp('Controller should not take any action')
elseif error > 0 && Uz < 0
disp('Open the control valve and supply more lifting gas')
elseif error < 0 && Uz < 0
disp('Object losing altitude')
else
disp('other value')
end
Object losing altitude
  댓글 수: 1
Telema Harry
Telema Harry 2021년 8월 10일
Thank you for the feedback @Scott MacKenzie.
I was intentionally avoiding the if statement as I have up to 10 different conditions and the switch statement is easier to read. I will just stick with the if statement.
thanks for the help.

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

추가 답변 (0개)

카테고리

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

제품


릴리스

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by