0
0
MATLABdata~5 mins

If-elseif-else statements in MATLAB

Choose your learning style9 modes available
Introduction

If-elseif-else statements help your program make choices. They run different code depending on conditions.

Deciding what message to show based on a user's score.
Choosing different actions depending on sensor readings.
Running special code only if a number is positive, negative, or zero.
Checking multiple conditions one after another to find the right match.
Syntax
MATLAB
if condition1
    % code to run if condition1 is true
elseif condition2
    % code to run if condition2 is true
else
    % code to run if none of the above conditions are true
end
Each condition is a logical test that results in true or false.
The elseif and else parts are optional but help check multiple cases.
Examples
Runs code only if x is greater than zero.
MATLAB
if x > 0
    disp('Positive number')
end
Checks if x is positive, zero, or negative and shows a message.
MATLAB
if x > 0
    disp('Positive')
elseif x == 0
    disp('Zero')
else
    disp('Negative')
end
Shows weather description based on temperature ranges.
MATLAB
if temperature > 30
    disp('Hot')
elseif temperature > 20
    disp('Warm')
else
    disp('Cold')
end
Sample Program

This program checks the temperature and prints if it is hot, warm, or cold.

MATLAB
temperature = 25;

if temperature > 30
    disp('It is hot outside.')
elseif temperature > 20
    disp('It is warm outside.')
else
    disp('It is cold outside.')
end
OutputSuccess
Important Notes

Always end your if-elseif-else block with end in MATLAB.

Conditions are checked in order. Once one is true, the rest are skipped.

You can have many elseif parts to check multiple conditions.

Summary

If-elseif-else lets your program choose between different actions.

Conditions are tested in order until one is true.

Use end to close the whole if block.