Borrar filtros
Borrar filtros

If Else Statement in a Switch function

5 visualizaciones (últimos 30 días)
Muhammad Aiman Al-Amin
Muhammad Aiman Al-Amin el 10 de Abr. de 2023
Editada: the cyclist el 10 de Abr. de 2023
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

Respuestas (2)

the cyclist
the cyclist el 10 de Abr. de 2023
You didn't end the if clause that is inside the first case statement.

Bhanu Prakash
Bhanu Prakash el 10 de Abr. de 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 comentarios
Muhammad Aiman Al-Amin
Muhammad Aiman Al-Amin el 10 de Abr. de 2023
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 el 10 de Abr. de 2023
Editada: the cyclist el 10 de Abr. de 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.

Iniciar sesión para comentar.

Categorías

Más información sobre Schedule Model Components en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by