TExcelTAD
Home › MATLAB / Octave › if, elseif, else

if, elseif, else

An if statement runs a block of code only when a condition is true. Every if block is closed with end. There are no braces and indentation is only for readability, although you should always indent.

matlab · try it yourself
temperature = 31;
if temperature > 30
    disp('It is hot today.')
end
disp('Done.')
It is hot today.
Done.

else and elseif

Add else for the case when the condition is false, and any number of elseif branches to test further conditions in order. Only the first true branch runs:

matlab · try it yourself
scores = [95 82 74 61 40];
for s = scores
    if s >= 90
        grade = 'A';
    elseif s >= 80
        grade = 'B';
    elseif s >= 70
        grade = 'C';
    elseif s >= 60
        grade = 'D';
    else
        grade = 'F';
    end
    fprintf('%d -> %s\n', s, grade);
end
95 -> A
82 -> B
74 -> C
61 -> D
40 -> F

Because the branches are checked from top to bottom, the elseif s >= 80 branch doesn't need to also check s < 90: a score of 90 or more never gets there.

Note: elseif is one word. Writing else if starts a new, nested if inside the else, which then needs its own end.

Combining conditions

Use && (and), || (or) and ~ (not) to build conditions from scalar tests:

matlab · try it yourself
age = 16;
withParent = true;
if age >= 18 || (age >= 12 && withParent)
    disp('Admitted')
else
    disp('Not admitted')
end

name = '';
if ~isempty(name)
    fprintf('Hello, %s\n', name);
else
    disp('Hello, stranger')
end
Admitted
Hello, stranger

Conditions on arrays

An if condition can be an array. It counts as true only if it is non-empty and all its elements are nonzero. This rule surprises people, so be explicit with all or any:

matlab · try it yourself
v = [3 5 -1];
if v > 0
    disp('implicit: all positive')
else
    disp('implicit: not all positive')
end
if any(v < 0)
    disp('explicit: at least one negative value')
end
if []
    disp('never printed')
else
    disp('an empty condition counts as false')
end
implicit: not all positive
explicit: at least one negative value
an empty condition counts as false

Writing if all(v > 0) or if any(v < 0) makes the meaning obvious to the reader.

Comparing text in conditions

Don't use == to compare char arrays in a condition: it compares character by character and fails when the lengths differ. Use strcmp (case-sensitive) or strcmpi (case-insensitive):

matlab · try it yourself
answer = 'Yes';
if strcmpi(answer, 'yes')
    disp('Confirmed')
end
try
    if answer == 'no'
        disp('no')
    end
catch err
    disp('== failed because the texts have different lengths')
end
Confirmed
== failed because the texts have different lengths

A worked example: leap years

A year is a leap year if it is divisible by 4, except century years, which must be divisible by 400:

matlab · try it yourself
years = [1900 2000 2023 2024];
for y = years
    if mod(y, 400) == 0
        leap = true;
    elseif mod(y, 100) == 0
        leap = false;
    elseif mod(y, 4) == 0
        leap = true;
    else
        leap = false;
    end
    fprintf('%d leap year: %d\n', y, leap);
end
1900 leap year: 0
2000 leap year: 1
2023 leap year: 0
2024 leap year: 1

The same logic fits in one vectorised line, without if at all: leap = mod(years, 4) == 0 & (mod(years, 100) ~= 0 | mod(years, 400) == 0). You'll see more of this style in the Vectorization lesson.

Test yourself

How is an if block closed in MATLAB?

  1. endif
  2. }
  3. end
  4. fi

With x = 85, which branch runs in if x >= 60 ... elseif x >= 80 ... end?

  1. Both
  2. The if branch only
  3. The elseif branch only
  4. Neither

When is if [1 0 1] considered true?

  1. Always
  2. Never, because not all elements are nonzero
  3. When any element is nonzero
  4. It is an error