Skip to main content
Logo image

Section 7.4 The if-else-end command

Here is the general syntax in MATLAB of the if-else-end command:
if condition
    command
    command
    ...
else
    command
    command
    ...
end
Let’s get back to our previous example but expand it with an else case:
answer = input('How much chocolate have you had today (1-10)? ');
if answer<5
   disp('Oh no! Be sure to eat more chocolate!');
else
   disp('Good for you. But have some more anyway!');
end
Here is what happens when you run this script and the user enters a number at least 5:
How much chocolate have you had today (1-10)? 6
Good for you. But have some more anyway!
Of course the program still acts the same way as before for a user input of less than 5.