Tips & Tricks – Indexing in Matlab

Consider a sample vector in Matlab.

Index with single value

Index with range of values

Select a range of elements using ‘:’ operator.

Example: Select elements with index ranging from 1 to 5.

Making a new vector by swapping two halves of the vector x

To refer the last element of the matrix x use ‘end’ operator

You can do arithmetic on the ‘end’ operator. Selecting all elements except the last element

Reversing the vector

Using the end operator in a range. Selecting from fifth element to the end

Replacing specific elements in the array by placing the new values on the right side of the expression. Replacing the values of ‘x’ at positions [2,5,8] with new values

Replacing specific elements with a same value. Replacing the values of ‘x’ at position [1 and 10] with 40

Two dimensional Arrays:

The two dimensional array elements are accessed with two subscript indices like x(i,j) – where ‘i’ represents row and ‘j’ represents column. Accessing the element located at second row and third column

The subscript indices can also be vectors. Selecting the elements in the first row – 4th,2nd and 1st column & third row – 4th,2nd and 1st column

The ‘:’ operator is the short form for 1:end. It is usually used to select all the elements in a specific column of row. Accessing all elements on the third row

Extracting the last row using the “end” operator and the “:” operator

Logical Indexing:

Used to select the elements of a matrix that satisfy some criteria given by an expression

Getting all elements of the matrix whose value is above 10

Getting the row and column subscripts of those elements using the “find” function.

Sometimes, when you run your script you might encounter ‘Inf’ (IEEE arithmetic representation for positive infinity) or -Inf( representation for negative infinity) values sitting in a matrix. See the following example

Your rest of the script may need you to fix this by replacing the Inf with 0. This can be achieved by using “isinf” function in Matlab. The “isinf” function returns a logical array which will specify whether an element is Inf (It also compares -Inf).

There are other functions similar to “isinf” like “isspace”,”isnan” etc.., that look for the specific condition to satisfy and returns a logical array depending on the result.

Rate this post : 1 Star2 Stars3 Stars4 Stars5 Stars (3 votes, average: 5.00 out of 5)


Other Resources on Matlab’s Matrix Indexing:

[1] Matlab documentation on Matrix indexing
[2]A Book detailing how MATLAB code can be written in order to maximize its effectiveness.
Richard K Johnson, “The Elements of MATLAB Style “, Cambridge University Press,ISBN-13: 978-0521732581

  • Niranjan

    Thanks! I had a similar document of my own but not half as comprehensive as this. I often forget the indexing as I shift from different languages.