MATLAB Answers


How do I end a program when a condition is met using only if-else-elseif statements?

Asked by Sam Jenkins on 9 Sep 2019
Latest activity Commented on by Sam Jenkins on 9 Sep 2019
I’m making a program where I need to have the program stop asking questions if an invalid input is entered by the user. How would I do this using only if-elseif-else statements, not using commands like return or break?


Why are you limiting yourself? Is this homework? Using keywords like return and break will make code much more readable and compact.
Yes, sorry if that’s against the rules of the board. I just don’t understand the general concepts of nesting if-else statements and can’t seem to make it work.

Sign in to comment.




1 Answer

Answer by Rik
on 9 Sep 2019
Edited by Rik
on 9 Sep 2019
 Accepted Answer

Something like this will work (edit to add nesting):
function out=MyFunction(in)
if in<1
if in==0.5
%do something
%do something different
elseif in==2
%do something else
%do nothing
%don't put code here
You could also use code at the beginning of your function to find out the type of code that should be run and then use that in a switch case structure.

  1 Comment

Sign in to comment.