Skip to content

MATLAB - End Function

The end keyword is a fundamental part of MATLAB’s syntax with two distinct and powerful uses:

  1. As a statement terminator: It marks the conclusion of a block of code, such as a loop, conditional statement, or function definition.
  2. As an indexing shortcut: It refers to the last element in a dimension of an array.

In MATLAB, many control structures and definitions require an end to explicitly define their boundaries. This ensures code is well-structured and unambiguous. Structures that require a terminating end include for, while, if/elseif/else, switch, try/catch, and function.

data = [10, -5, 0, 8, -3];
for k = 1:length(data) % Start of the for-loop block
if data(k) < 0 % Start of the if-statement block
fprintf('Found a negative number at index %d.\n', k);
end % Terminates the if-statement block
end % Terminates the for-loop block

While end is sometimes optional for functions in simple script files, it becomes mandatory in more structured scenarios to ensure clarity and proper scope:

  • Nested Functions: When you define a function inside another function, both the outer and inner functions must be terminated with end.
  • Local Functions: If a script file or function file contains multiple, separate functions (local functions), every function within that file must be terminated with end.
% parent_function.m
function output = parent_function(input)
% This is the main function
temp = local_helper(input); % Call to local function
output = temp + 5;
end % Mandatory 'end' for the parent function
function result = local_helper(x)
% This is a local function within the same file
result = x * 2;
end % Mandatory 'end' for the local function

This is a powerful feature for writing robust and readable code. end can be used in an array index to refer to the last element along that dimension.

% Create a sample vector
A = 10:10:100; % A = [10, 20, 30, ..., 100]
% Access the last element
last_el = A(end);
% Access the second-to-last element
second_to_last_el = A(end-1);
% Access a range from the 5th element to the end
sub_vector = A(5:end);
disp(['Last element: ', num2str(last_el)]); % Output: 100
disp(['Second-to-last element: ', num2str(second_to_last_el)]); % Output: 90
disp('Sub-vector from 5th to end:'); % Output: [50, 60, 70, 80, 90, 100]
disp(sub_vector);

Example: Accessing Rows and Columns of a Matrix

Section titled “Example: Accessing Rows and Columns of a Matrix”
% Create a 4x4 magic square
M = magic(4);
disp('Original Matrix:');
disp(M);
% Access the entire last row
last_row = M(end, :);
disp('Last Row:');
disp(last_row);
% Access the entire last column
last_col = M(:, end);
disp('Last Column:');
disp(last_col);
% Access the element in the last row and last column
bottom_right_corner = M(end, end);
disp(['Bottom-Right Element: ', num2str(bottom_right_corner)]);
% --- Partial Output ---
% Original Matrix:
% 16 2 3 13
% 5 11 10 8
% 9 7 6 12
% 4 14 15 1
% Last Row:
% 4 14 15 1
% Last Column:
% 13
% 8
% 12
% 1
% Bottom-Right Element: 1

Best Practice: Writing Robust Code with end

Section titled “Best Practice: Writing Robust Code with end”

Using end for indexing makes your code more dynamic and less prone to errors. Consider a function that needs to process the last three elements of an input array.

% Brittle, hardcoded approach
function process_brittle(arr)
len = length(arr);
subset = arr(len-2:len); % Fails if arr has fewer than 3 elements!
disp(subset);
end
% Robust, modern approach
function process_robust(arr)
if numel(arr) >= 3
subset = arr(end-2:end);
disp(subset);
else
disp('Array is too small.');
end
end
process_robust([1, 2, 3, 4, 5]); % Works
process_robust([10, 20]); % Handled gracefully

The robust approach using end is cleaner to read and, when combined with a size check, prevents runtime errors, making your code more reliable.