The end keyword terminates a block of code or denotes the last index in an indexing expression.

## Preparation

Create a matrix using the following code:

A = [1, 5, 2; 3, 6, 4];

## end

The end keyword terminates a block of code. It also behaves as a function, and denotes the last index in linear indexing or subscript indexing expressions (Table 1).

Table 1. Common uses of the end keyword in linear indexing and subscript indexing expressions.
Code Description
A(end,:) end is used in the row part of a subscript indexing expression, so it denotes the index of the last row in A (i.e. 2)
A(:,end) end is used in the column part of a subscript indexing expression, so it denotes the index of the last column in A (i.e. 3)
A(end) end is used in a linear indexing expression, so it denotes the linear index of the last element in A (i.e. 6)

## Examples

The end keyword is frequently used in conjunction with the colon operator (i.e. :). Once you understand how they work, you can build concise indexing expressions.

% Element at the last row, second column of A
target = A(end,2);
% Elements in the last row
lastRow = A(end,:);
% Elements in the penultimate column
penultimateCol = A(:,end-1);
% Last element
lastElement = A(end);
% Elements whose linear index is an odd number
atOddIdxs = A(1:2:end);
% Elements in reverse order
reverse = A(end:-1:1);

You can use end in statements that grow a matrix, although in these cases the matrix must already exist.

% Add a new column and set values to -1
A(:,end+1) = -1;

I recommend the following books to learn more on matrix manipulation in MATLAB:

1. This book was the winner of a 2017 Textbook Excellence Award. The second chapter explains the colon operator, linear indexing, and subscript indexing.

2. MATLAB for Engineers (5th Edition)

This excellent book is especially oriented to engineers and scientists who want to learn MATLAB programming. The fourth chapter is completely dedicated to matrix manipulation.

I also recommend the following page in the MATLAB help documentation, and the other tutorials in this series.

doc end;

## Exercise

A student who did not know how to use the end keyword, wrote the following code to calculate the sum of certain elements in a two-dimensional matrix X of a size greater than or equal to 2×2.

[rowsCount,colsCount] = size(X);

sum1 = X(1,1) + X(1,colsCount);
sum2 = X(2,1) + X(rowsCount,colsCount);
sum3 = sum(X(rowsCount-1,:));
sum4 = sum(X(rowsCount,2:2:colsCount));
sum5 = sum(X(:,colsCount)) + sum(X(rowsCount-1,:)) + X(rowsCount,colsCount);

Refactor the code using the end keyword. Check that the original code and the refactored code yield the same result.

## Source code

I hope you have learned how to use the end keyword in MATLAB. It is a powerful tool to build concise indexing expressions. The source code developed in this tutorial is available at this page.