If Else Statement in a Switch function
37 ビュー (過去 30 日間)
古いコメントを表示
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/1350999/image.png)
Thank you in advance
0 件のコメント
回答 (2 件)
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 件のコメント
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.
参考
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!