Skip to main content
Logo image

Section 7.3 The if-end command

We’ll now get into various ways to branch your code.
The if-end command syntax in its most straight-forward form is here:
if condition
    command
    command
    ...
end
Here are some example conditions:
if (a < b)
if (c >= 5)
if (a == b)
if (0 ~= debug)
if (a ~= 0)
if ((d < h) && (x > 7))
if ((age <= 21) || (IQ> 200))
Let’s take a look at an example. Suppose you have created the following MATLAB script:
answer = input('How much chocolate have you had today (1-10)? ');
if answer<5
   disp('Oh no! Be sure to eat more chocolate!');
end
Here is what happens when you run this script:
How much chocolate have you had today (1-10)? 4
Oh no! Be sure to eat more chocolate!
Of course we might also wish for an else case and this is what the next section is about.