Tutorial

Linear Indexing in MATLAB

Linear indexing allows to reference elements in a matrix according to their position in the in-memory representation of the matrix.

Preparation

Create a matrix using the following code:

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

Linear indexing

MATLAB supports three ways to reference elements in a matrix:

MATLAB stores matrices in memory as a column vector. The position of each element in this vector is known as its linear index (Fig. 1). To use linear indexing, specify the linear index of the target element.

Representation of linear indexing in 2D and 3D matrixes.
Figure 1. Linear index of elements in 2D and 3D matrices.

Examples

In the indexing expression use a scalar to denote a single element, or a set of indices to denote multiple elements. To create a set of indices, use the colon operator (i.e. :) or the concatenation operator (i.e. []).

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

Further reading

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

  1. MATLAB: A Practical Introduction to Programming and Problem Solving (4th Edition)

    This book was the winner of a 2017 Textbook Excellence Award. Linear 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 linear 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. Positions whose linear index is an even number

Source code

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

Share

Your friends may need this knowledge to complete a task. Share this tutorial.