Skip to content

MATLAB - If Else Statement

MATLAB - Conditional Statements: if, elseif, else

Section titled “MATLAB - Conditional Statements: if, elseif, else”

Conditional statements allow your code to make decisions and execute different blocks of code based on whether certain conditions are met. The fundamental structure for this in MATLAB is the if...elseif...else...end block.

The simplest form of a conditional executes a block of code only if a given expression is true.

if <expression>
% Statement(s) to execute if expression is true
end

An if statement can be followed by an optional else statement, which executes when the if expression is false. This provides a way to handle two possible outcomes.

if <expression>
% Statement(s) to execute if expression is true
else
% Statement(s) to execute if expression is false
end
a = 100;
% Check the boolean condition
if a < 20
fprintf('a is less than 20.\n');
else
fprintf('a is NOT less than 20.\n');
end
fprintf('The final value of a is: %d\n', a);

When executed, this code produces the following result:

a is NOT less than 20.
The final value of a is: 100

Handling Multiple Conditions: if...elseif...else...end

Section titled “Handling Multiple Conditions: if...elseif...else...end”

For situations with more than two possible outcomes, you can use one or more elseif statements. MATLAB checks the conditions sequentially. The first one that evaluates to true has its code block executed, and the rest of the structure is skipped.

if <expression1>
% Executes if expression1 is true
elseif <expression2>
% Executes if expression1 is false AND expression2 is true
else
% Executes if all preceding expressions are false
end

Let’s write a script to assign a letter grade based on a numerical score.

score = 85;
if score >= 90
grade = 'A';
elseif score >= 80
grade = 'B';
elseif score >= 70
grade = 'C';
elseif score >= 60
grade = 'D';
else
grade = 'F';
end
fprintf('A score of %d results in a grade of ''%s''.\n', score, grade);

Output for score = 85:

A score of 85 results in a grade of 'B'.

You can create more complex conditions using logical operators:

  • && : Logical AND
  • || : Logical OR
  • ~ : Logical NOT
temperature = 25; % degrees Celsius
isRaining = false;
if temperature > 20 && ~isRaining
disp('It is a pleasant day for a walk!');
elseif temperature < 5 || isRaining
disp('Better to stay indoors today.');
end

When you need to check a single variable against a list of discrete values, a switch statement can be cleaner and more readable than a long if...elseif... chain.

matlab_decisions.htm