Skip to content

MATLAB - If…Elseif Else Statement

MATLAB - Conditional Control Flow: if-elseif-else

Section titled “MATLAB - Conditional Control Flow: if-elseif-else”

Conditional statements are the bedrock of programming logic, allowing your code to make decisions and execute different blocks of code based on specific criteria. In MATLAB, the if...elseif...else structure is the primary tool for implementing this decision-making process.

When structuring your conditional logic, keep these rules in mind:

  • An if block can have zero or more elseif blocks.
  • An if block can have at most one else block, which must come after all elseif blocks.
  • As soon as a condition in an if or elseif statement evaluates to true, its corresponding block of code is executed, and the entire if...end structure is exited. No subsequent conditions are tested.
if <condition_1>
% Code to execute if condition_1 is true
<statements_1>
elseif <condition_2>
% Code to execute if condition_1 is false AND condition_2 is true
<statements_2>
else
% Code to execute if all preceding conditions are false
<statements_3>
end

Let’s write a script that assigns a letter grade based on a numeric score. This is a classic use case for the if-elseif-else structure. Create a script file named assignGrade.m and add the following code:

% A script to determine a letter grade from a numeric score
score = 85; % Assign a test score
fprintf('The score is %d.\n', score);
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('The corresponding letter grade is: %c\n', grade);

When you run this script, the output will be:

The score is 85.
The corresponding letter grade is: B

Try changing the score variable to other values like 95, 72, or 50 to see how the logic branches to different outcomes.

When you need to compare a single variable against a list of discrete, specific values (e.g., strings or integers), a switch statement can be cleaner and more readable than a long if-elseif-else chain.

choice = 'Option B';
switch choice
case 'Option A'
disp('Executing action for Option A.');
case 'Option B'
disp('Executing action for Option B.');
case {'Option C', 'Option D'} % Grouping cases
disp('Executing shared action for C or D.');
otherwise
disp('Invalid choice.');
end
  • = vs. ==: A frequent beginner mistake is using a single equals sign (=), which is for assignment, instead of a double equals sign (==), which is for comparison. This will cause an error.
  • Floating-Point Comparisons: Avoid direct equality checks (==) for floating-point numbers due to precision issues. Instead, check if the absolute difference is within a small tolerance. For example: if abs(a - b) < 1e-9.
  • Logical Operators: Use short-circuiting operators && (AND) and || (OR) for scalar logical conditions. They stop evaluating as soon as the outcome is determined, which is more efficient. Use element-wise operators & and | when working with arrays.
  • Avoid Deep Nesting: Deeply nested if statements are hard to read and debug. If your logic goes more than 2-3 levels deep, consider refactoring your code by breaking it into smaller functions or using a different approach.
  • Testing All Paths: When testing your code, ensure you have test cases that cover every branch of your if-elseif-else statement to prevent hidden bugs.