Subscript indexing allows to reference elements in a matrix according to their position in each dimension.

Preparation

Create a matrix using the following code:

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

Subscript indexing

MATLAB supports three ways to reference elements in a matrix:

To use subscript indexing, specify the index of the target element in each dimension. The first index denotes row, the second index denotes column, the third index denotes plane, and so on (Fig. 1).

Examples

In any part of the indexing expression, use a scalar or a set of indices to denote a subset of the corresponding dimension, or the colon operator (i.e. `:`) to mean the entire dimension.

``````% Sum of the first and the last element in A
partialSum = A(1,1) + A(2,3); % 1 + 4 = 5``````
``````% Elements in the second row
secondRow = A(2,:);``````
``````% Elements from the second to the third column
lastTwoCols = A(:,2:3);``````
``````% Elements in the first and the third column
borderCols = A(:,[1,3]);``````
``````% Elements in the second row but in the first and the third column
target = A(2,[1,3]);``````

I recommend the following books to learn more on subscript indexing in MATLAB:

1. This book was the winner of a Textbook Excellence Award. Subscript indexing, and other indexing methods, are explained clearly in the second chapter.

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 other tutorials in this series.

Exercise

Consult the help documentation of the `rand` function. Create a matrix of random numbers having three rows, four columns, and two planes.

Use subscript indexing to get the elements in the:

1. First row of the first plane
2. Last three columns of the first plane
3. Last two rows of the second plane
4. Intersection of the last two rows with the first two columns of the second plane
5. First row of each plane

Source code

I hope you have learned how to use subscript indexing in MATLAB. The source code developed in this tutorial is available at this page.