Tutorial

A Deeper Look on Logical Indexing in MATLAB

Logical indexing allows to reference elements in a matrix using a logical matrix as index.

Preparation

Create a matrix using the following code:

A = magic(3);

Logical indexing

The syntax to use logical indexing is A(B), where A is the matrix being accessed and B is a logical matrix.

% Logical indexing expression
r = A(A>7);

Requirement: The number of elements in the logical matrix B must be lower than or equal to the number of elements in the matrix being accessed A. In practice, they have the same shape normally.

How it works

MATLAB processes logical indexing expressions A(B) as follows (Fig. 1):

  1. Get both matrices in the form that they are stored in memory
  2. If B has less elements than A, assume the missing values as false
  3. Find the elements in A referenced by true values in B
Representation of logical indexing in MATLAB.
Figure 1. Representation of logical indexing in MATLAB.

Examples

Logical indexing is extremely powerful when it is combined with linear indexing or subscript indexing.

% Elements greater than 3 in the first two columns of A
expExample1 = A > 3;
expExample1(:,3) = false;
resultExample1 = A(expExample1);
% Elements greater than 4 in odd linear positions
expExample2 = A > 4;
expExample2(2:2:end) = false;
resultExample2 = A(expExample2);
% Set to 0 the elements greater than 5 in the 1st/3rd rows
expExample3 = A > 5;
expExample3(2,:) = false;
A(expExample3) = 0;

Further reading

I recommend the following books to learn more on logical 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. Logical 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, and get the values:

  1. Greater than 0.5 in the first column of each plane
  2. Lower than 0.5 in the last two columns of the second plane
  3. Greater than 0.25 and lower than 0.75 in linear positions multiple of 3

Source code

I hope you have acquired a deeper knowledge on how logical indexing works 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.