Skip to content

MATLAB - If End Statement

MATLAB - Conditional Control Flow: The if...end Statement

Section titled “MATLAB - Conditional Control Flow: The if...end Statement”

In programming, we often need to execute different blocks of code based on certain conditions. MATLAB provides the if...end statement for this purpose. It allows your program to make decisions and follow different paths, forming the basis of conditional logic.

The basic structure of a conditional block in MATLAB uses the if, elseif, else, and end keywords.

if <logical_expression_1>
% Statement(s) to execute if logical_expression_1 is true
elseif <logical_expression_2>
% Statement(s) to execute if logical_expression_1 is false
% AND logical_expression_2 is true
else
% Statement(s) to execute if all preceding expressions are false
end
  • An if block can exist on its own.
  • elseif and else are optional and provide alternative paths.
  • You can have multiple elseif blocks, but only one else block.
  • The entire structure must be terminated by a single end keyword.

You can visualize the logic flow as a series of questions:

Start
|
v
+-------------------------+
| Is condition_1 true? | --(Yes)--> [Execute Code Block 1] --+
+-------------------------+ |
| (No) |
v |
+-------------------------+ |
| Is condition_2 true? | --(Yes)--> [Execute Code Block 2] --+
+-------------------------+ |
| (No) |
v |
[Execute 'else' Block] -----------------------------------------+
| |
v |
End <-----------------------------------------------------------+

Let’s write a script that classifies a temperature reading. Create a script file named classifyTemperature.m and add the following code:

% Define a temperature in Celsius
temperatureC = 23.5;
% Check the condition and classify the temperature
if temperatureC < 0
classification = 'Freezing';
elseif temperatureC >= 0 && temperatureC < 15
classification = 'Cold';
elseif temperatureC >= 15 && temperatureC < 25
classification = 'Moderate';
else % temperatureC >= 25
classification = 'Warm';
end
% Display the result to the command window
% The fprintf function formats and prints the output string.
% %g is a placeholder for a floating-point number.
% %s is a placeholder for a string.
% \n creates a new line.
fprintf('A temperature of %g C is considered %s.\n', temperatureC, classification);

When you run this script from the MATLAB Command Window, it will display the following result:

A temperature of 23.5 C is considered Moderate.

Always use && for logical AND and || for logical OR within if statements. These are “short-circuiting” operators. For A && B, MATLAB will not evaluate B if A is false. This is efficient and can prevent errors, for example, when checking if a variable exists before using it.

MATLAB is optimized for array and matrix operations. While if statements are essential, avoid using them inside loops to process array elements one-by-one. Instead, use logical indexing. This is a core concept of idiomatic MATLAB programming and is significantly faster.

% --- SLOW: Using a loop with an if statement ---
data = [-10, 5, 20, 30, -2];
for i = 1:length(data)
if data(i) < 0
data(i) = 0; % Replace negative values with 0
end
end
% --- FAST: Using logical indexing (Vectorization) ---
data = [-10, 5, 20, 30, -2];
negative_indices = (data < 0);
% The line above creates a logical array: [1, 0, 0, 0, 1]
data(negative_indices) = 0; % Use the logical array to set values
% A more concise version of the above:
data(data < 0) = 0;
  • Assignment vs. Comparison: A very common mistake is using = (assignment) instead of == (comparison) inside an if condition. For example, if x = 5 will cause an error. It should be if x == 5.
  • Floating-Point Comparison: Be careful when comparing floating-point numbers for exact equality due to precision limitations. Instead of if x == 0.1, it’s safer to check if the difference is within a small tolerance: if abs(x - 0.1) < 1e-9.
  • Mismatched end: Forgetting an end statement or having too many will cause a syntax error. The MATLAB Editor is excellent at helping you find these by highlighting matching keywords and auto-indenting your code (Ctrl+I or Cmd+I).