If Else Statement in a Switch function

조회 수: 47 (최근 30일)
Muhammad Aiman Al-Amin
Muhammad Aiman Al-Amin 2023년 4월 10일
편집: the cyclist 2023년 4월 10일
As the title stated, I want to make a program where I can input if else statement into a switch case, however most source I see on the forum just straight up put the condition into the case without if else statement, which prevent from getting the code that I wanted. Is there a way to make it work? Or it is impossible to put the two function together without removing the if else statement?
Thank you in advance

답변 (2개)

the cyclist
the cyclist 2023년 4월 10일
You didn't end the if clause that is inside the first case statement.

Bhanu Prakash
Bhanu Prakash 2023년 4월 10일
Hi Aiman,
As per my understanding, you want to use an "if-else" statement in "case" statement.
The answer to your question is "Yes". You can use "if-else" statement in a "case" statement. But the error that you got is due to the usage of incorrect syntax in the "case" statement.
I have attached the edited part of the code, for your reference:
switch n
case 1
if gread <70
disp('Your glucose level is too low.');
elseif (70 <=gread) && (gread <=100)
disp('Congratulations, your glucose level is normal.');
elseif (101 <=gread) && (gread <=125)
disp('You are diagnosed as pre-diabetes');
else
disp('You are diagnosed as diabetes');
end
case 2
if gread < 70
disp('Your glucose level is too low.');
elseif (70 <=gread) && (gread <=100)
disp('Congratulations, your glucose level is normal.');
elseif (101 <=gread) && (gread <=125)
disp('You are diagnosed as pre-diabetes');
else
disp('You are diagnosed as diabetes');
end
end
You can refer to the documentation of "case" statement, for more info:
Hope this answer helps you.
Thanks,
Bhanu Prakash.
  댓글 수: 2
Muhammad Aiman Al-Amin
Muhammad Aiman Al-Amin 2023년 4월 10일
Thank you very much for the asnwer!
It seems that I need to put 'end' for each if else statement.
May I ask, in this case, why is there no need to put 'otherwise' case in the switch function? Is the otherwise statement optional in switch function?
the cyclist
the cyclist 2023년 4월 10일
편집: the cyclist 2023년 4월 10일
Yes, the otherwise block is optional. (This is mentioned in the documentation.)
I think it is considered best practice to include one, though, to guard against the possibility of inadvertentlyl not covering all possible cases.

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

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by