If Else Statement in a Switch function
35 views (last 30 days)
Show older comments

Thank you in advance
0 Comments
Answers (2)
Bhanu Prakash
on 10 Apr 2023
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 Comments
the cyclist
on 10 Apr 2023
Edited: the cyclist
on 10 Apr 2023
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.
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!