Tutorial

Logical Indexing in MATLAB

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

Preparation

Create two matrices using the following code:

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

Logical indexing

MATLAB supports three ways to reference elements in a matrix:

Logical indexing uses a logical matrix as index, where the position of true values indicates the elements of interest in the matrix being accessed. So, the expression A(B) returns the following result:

ans =
     1
     6

Examples

The common use of logical indexing is to reference the elements that satisfy a certain condition. In rare cases you will create the logical matrix manually.

% Elements in A greater than or equal to 3
geThree = A(A>=3);
% Elements lower than 6
lSix = A(A<6);
% Elements greater than 1 and lower than 6
rangeExp = (A > 1) & (A < 6);
range = A(rangeExp);
% Set to 0 elements lower than 5
A(A<5) = 0;

Note: When the logical expression is large or uses logical operators, best practices suggest to write it independently in a new line.

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, but especially this tutorial.

Exercise

Consult the help documentation of the functions magic and mod. Create a matrix of size 4×4 and get the elements that are:

  1. Greater than 5 and lower than 10
  2. Divisible by 2 and greater than 7
  3. Greater than 4, divisible by 3, and not greater than 15

Additionally set odd numbers to 0.

Source code

I hope you have learned how to use logical 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.