If Else Statement in a Switch function

18 次查看(过去 30 天)
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
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 中查找有关 Modeling 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by