Linear indexing and subscript indexing are common forms to reference elements in a matrix.

## Preparation

Create a matrix using the following code:

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

## Index conversion

MATLAB supports three ways to reference elements in a matrix:

To convert linear indices to their equivalent subscripts, use the function `ind2sub`. For the opposite, use `sub2ind`.

``````[rowSub,colSub,dim3Sub,...,dimNSub] = ind2sub(siz,linearInd);
linearInd = sub2ind(siz,rowSub,colSub,dim3Sub,...,dimNSub);``````

## Examples

`ind2sub` takes as input the size of the matrix, and the linear indices, and returns the corresponding subscripts grouped by dimension. `sub2ind` takes as input the size of the matrix, and the subscripts grouped by dimension, and returns the corresponding linear indices.

``````% Get subscripts equivalent to A(5) and A(6)
[rowSub,colSub] = ind2sub(size(A),[5,6]);``````
``````% Get linear indices equivalent to A(1,3) and A(2,3)
linearInd = sub2ind(size(A),[1,2],[3,3]);``````

Note: In the case of `sub2ind`, the subscript vectors must have the same size, and this size determines the shape of the output.

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

1. This book was the winner of a Textbook Excellence Award. Linear indexing and subscript indexing 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 following pages in the MATLAB help documentation, and the other tutorials in this series.

``````doc ind2sub;
doc sub2ind;``````

## Exercise

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

1. Calculate the subscripts equivalent to `X(2)`, `X(6)` and `X(15)`
2. Calculate the linear indices equivalent to `X(1,1,1)`, `X(3,4,1)` and `X(2,3,2)`

In all prior cases, use only one statement per clause, and visually check that the subscripts and linear indices reference the same data.

## Source code

I hope you have learned how to convert linear indices to subscripts, and viceversa, in MATLAB. The source code developed in this tutorial is available at this page.