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.
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:
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);
end95 -> 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:
elseifis one word. Writingelse ifstarts a new, nestedifinside theelse, which then needs its ownend.
Combining conditions
Use && (and), || (or) and ~ (not) to build conditions from scalar tests:
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')
endAdmitted
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:
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')
endimplicit: 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):
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')
endConfirmed
== 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:
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);
end1900 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?
endif}endfi
With x = 85, which branch runs in if x >= 60 ... elseif x >= 80 ... end?
- Both
- The
ifbranch only - The
elseifbranch only - Neither
When is if [1 0 1] considered true?
- Always
- Never, because not all elements are nonzero
- When any element is nonzero
- It is an error