Skip to content

MATLAB - Decisions

Decision-making structures are a fundamental part of programming. They allow your code to respond differently to different situations, making your programs intelligent and dynamic. These structures require you to specify one or more conditions to be evaluated. Based on whether a condition is true or false, a specific block of code is executed.

Think of it like a fork in the road. A condition (e.g., “Is it raining?”) determines which path your program takes. If true, it might execute the ‘bring an umbrella’ code. If false, it might execute the ‘wear sunglasses’ code. This control over the program’s execution flow is essential for almost any task.

MATLAB provides a standard set of decision-making statements, common to many programming languages. Here is a summary of the available structures:

No.Statement & Description
1if … end statement
An if ... end statement consists of a logical expression followed by one or more statements that execute only if that expression is true.
2if…else…end statement
An if statement can be followed by an optional else block. The else block executes when the logical expression is false.
3if…elseif…else…end statements
This structure is used to decide between several (more than two) alternatives. As soon as an if or elseif expression is found to be true, the corresponding statements are executed, and the rest of the structure is skipped.
4nested if statements
You can use one if or elseif statement inside another. However, for complex logic, this can become hard to read and should be used with care.
5switch statement
A switch statement provides a clean way to test a single variable for equality against a list of possible values.
6nested switch statements
Similar to nested if statements, you can use a switch statement inside another switch statement.

This is the simplest form of decision making. The code block is executed only if the condition is met.

%% Example: Check if a temperature reading indicates a fever
temperature = 38.5;
if temperature > 37.5
disp('Warning: High temperature detected. Potential fever.');
end
% --- Output ---
% Warning: High temperature detected. Potential fever.

This structure provides an alternative path for when the condition is false.

%% Example: Check if a student passed or failed
score = 65;
passingGrade = 50;
if score >= passingGrade
disp('Congratulations, you passed!');
else
disp('You did not pass. Better luck next time.');
end
% --- Output ---
% Congratulations, you passed!

This is the ideal structure for checking multiple, mutually exclusive conditions. It is more readable than deeply nested if statements.

%% Example: Assign a letter grade based on a score
score = 88;
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 grade is: %s\n', grade);
% --- Output ---
% The grade is: B

A switch statement is an excellent choice when you need to check a single variable against a list of specific, discrete values. It works with numbers, character vectors, and modern string or categorical arrays.

%% Example: Respond based on a selected menu option (using strings)
% In modern MATLAB, using strings (double quotes) is preferred for text.
menuSelection = "Save";
switch menuSelection
case "Open"
disp('Opening file...');
case "Save"
disp('Saving file...');
case "Close"
disp('Closing file...');
otherwise
disp('Invalid selection.');
end
% --- Output ---
% Saving file...
  • Use elseif for Clarity: Avoid deeply nested if statements. An if...elseif...else chain is much easier to read and maintain.
  • Leverage Short-Circuiting: MATLAB uses short-circuiting for && (AND) and || (OR). In an expression like conditionA && conditionB, conditionB is only evaluated if conditionA is true. This can be used to prevent errors, for example: if (x ~= 0) && (1/x > 5), which prevents a division-by-zero error.
  • Handle the ‘Otherwise’ Case: When using switch or if...elseif, it’s good practice to include a final else or otherwise block to handle any unexpected values. This makes your code more robust.
  • Compare Floating-Point Numbers Carefully: Due to how computers store floating-point numbers, using == for direct comparison can be unreliable. For example, 0.1 + 0.2 == 0.3 is false! Instead, check if the absolute difference is within a small tolerance: if abs(a - b) < 1e-9.
  • Assignment vs. Comparison: A very common mistake is using the assignment operator = instead of the comparison operator == inside an if condition (e.g., if x = 5). The MATLAB Editor will usually flag this with a warning.
  • Missing end Keyword: Every if, switch, for, and while block must be closed with an end keyword. The MATLAB Editor helps by auto-indenting and highlighting matching keywords, making it easier to spot a missing end.
  • Strings vs. Character Vectors: In older MATLAB code, you’ll see single quotes ('text') for character vectors. Modern MATLAB heavily favors double quotes ("text") for string objects, which are more flexible. Be aware of the type when making comparisons.