Conditional Statements

A condition is true only if it is non-empty and all its elements are nonzero.

Concept

if / elseif / else A condition is true only if it is non-empty and all its elements are nonzero. So if [] is false, and if [1 1 0] is false. Use any/all to make array conditions explicit.

switch works with numbers and text (character vectors; compared like strcmp). Unlike C, cases don't fall through and there is no break.

if condition
    ...
elseif other_condition
    ...
else
    ...
end
switch value
    case 1
    case {2, 3}          % several values
    otherwise
end

Why It Matters

Classification (limits, fault codes, operating modes), input validation and state machines all depend on conditions.

Syntax

if v < lo, status = 'LOW'; elseif v > hi, status = 'HIGH'; else, status = 'OK'; end
switch lower(mode), case 'fast', ...; case {'eco', 'normal'}, ...; otherwise, ...; end

Example

9.1 Classifying voltages and trouble codes

voltages = [10.5 12.6 14.9 13.2];
for v = voltages
    if v < 11.5
        status = 'LOW';
    elseif v > 14.8
        status = 'HIGH';
    else
        status = 'OK';
    end
    fprintf('%.1f V -> %s\n', v, status)
end

codes = {'P0A80', 'U0100', 'B1000', 'X9999'};
for k = 1:numel(codes)
    switch codes{k}(1)
        case 'P'
            system = 'Powertrain';
        case {'C', 'B'}
            system = 'Chassis/Body';
        case 'U'
            system = 'Network';
        otherwise
            system = 'Unknown';
    end
    fprintf('%s -> %s\n', codes{k}, system)
end

x = [];
if x
    disp('empty is true')
else
    disp('an empty array is treated as false in if')
end
if [1 1 0]
    disp('all nonzero')
else
    disp('if [1 1 0] is false: every element must be nonzero')
end

Expected Result

The last two blocks show MATLAB's rule for array conditions: an empty array and an array containing any zero are both false.

10.5 V -> LOW
12.6 V -> OK
14.9 V -> HIGH
13.2 V -> OK
P0A80 -> Powertrain
U0100 -> Network
B1000 -> Chassis/Body
X9999 -> Unknown
an empty array is treated as false in if
if [1 1 0] is false: every element must be nonzero

Common Mistakes

Using = instead of == in a condition.

Using an array in if without any/all and misunderstanding the result.

Forgetting end.

Writing if 11.5 <= v <= 14.8 — it evaluates (11.5 <= v) <= 14.8, which is always true.

Best Practices

Use &&/|| in scalar conditions.

Prefer switch for many discrete cases, especially text.

Write range checks as v >= lo && v <= hi.

Interview Relevance

Medium: "what is true in an if for an array?", "does switch fall through?", "how do you test a range?".

Practice Questions

Classify a battery state of charge (0–100) into Empty/Low/Medium/High/Full.

Use switch to map a UDS service ID (hex text) to its name.

Print whether a year is a leap year.

What does if 'false' do, and why?

Quick Quiz

Q1. (Multiple choice) When is if A true for a vector A? A) If any element is nonzero B) If all elements are nonzero and A is non-empty C) Always D) Never Answer: B (verified).

Q2. (Predict the output) For v = 14.9, which branch of the voltage example runs?

Answer: HIGH (verified).

Q3. (True/False) MATLAB switch cases fall through to the next case without break.

Answer: False. Q4. (Find the bug) if 11.5 <= v <= 14.8, disp('OK'), end prints OK for v = 20.

Answer: It is (11.5 <= v) <= 14.8 → 1 <= 14.8 → true. Write v >= 11.5 && v <= 14.8.

Coding Challenge

Write a script that grades exam scores [95 83 71 64 42] as A (≥90), B (≥80), C (≥70), D (≥60) or F and prints each score with its grade.

scores = [95 83 71 64 42];
for s = scores
    if s >= 90
        g = 'A';
    elseif s >= 80
        g = 'B';
    elseif s >= 70
        g = 'C';
    elseif s >= 60
        g = 'D';
    else
        g = 'F';
    end
    fprintf('%d -> %s\n', s, g)
end