MATLAB - End Function
MATLAB - The end Keyword
Section titled “MATLAB - The end Keyword”The end keyword is a fundamental part of MATLAB’s syntax with two distinct and powerful uses:
- As a statement terminator: It marks the conclusion of a block of code, such as a loop, conditional statement, or function definition.
- As an indexing shortcut: It refers to the last element in a dimension of an array.
1. Using end to Terminate Code Blocks
Section titled “1. Using end to Terminate Code Blocks”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.
Example: if and for Statements
Section titled “Example: if and for Statements”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 blockend % Terminates the for-loop blockMandatory end in Function Definitions
Section titled “Mandatory end in Function Definitions”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.mfunction 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 function2. Using end for Array Indexing
Section titled “2. Using end for Array Indexing”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.
Example: Accessing Elements of a Vector
Section titled “Example: Accessing Elements of a Vector”% Create a sample vectorA = 10:10:100; % A = [10, 20, 30, ..., 100]
% Access the last elementlast_el = A(end);
% Access the second-to-last elementsecond_to_last_el = A(end-1);
% Access a range from the 5th element to the endsub_vector = A(5:end);
disp(['Last element: ', num2str(last_el)]); % Output: 100disp(['Second-to-last element: ', num2str(second_to_last_el)]); % Output: 90disp('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 squareM = magic(4);disp('Original Matrix:');disp(M);
% Access the entire last rowlast_row = M(end, :);disp('Last Row:');disp(last_row);
% Access the entire last columnlast_col = M(:, end);disp('Last Column:');disp(last_col);
% Access the element in the last row and last columnbottom_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: 1Best 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 approachfunction process_brittle(arr) len = length(arr); subset = arr(len-2:len); % Fails if arr has fewer than 3 elements! disp(subset);end
% Robust, modern approachfunction process_robust(arr) if numel(arr) >= 3 subset = arr(end-2:end); disp(subset); else disp('Array is too small.'); endend
process_robust([1, 2, 3, 4, 5]); % Worksprocess_robust([10, 20]); % Handled gracefullyThe robust approach using end is cleaner to read and, when combined with a size check, prevents runtime errors, making your code more reliable.