Matlab

How to Implement Logical Indexing in MATLAB?

MATLAB facilitates us with different approaches to accessing the array elements. One such approach is logical indexing. Logical indexing is a way to access the array elements using one or more logical conditions. The main objective to write this article is to teach MATLAB users about the logical indexing of an array and how it works in MATLAB.

What is Logical Indexing in MATLAB?

Logical indexing is a useful method used for indexing the array elements. Mostly this method is used when we work with conditional statements. When a logical condition is applied to an array it returns logical values a true 1 or false 0 corresponding to array values on their respective indices.

How to Implement Logical Indexing in MATLAB?

The logical indexing of an array can be performed using the following instructions.

  • Declare an array of any size.
  • Apply one or more logical conditions on the array using the logical operators.
  • Index the array elements that satisfy the given logical condition.
  • Use this logical indexing to extract the array elements.

Examples

Follow the given examples to learn how logical indexing works in MATLAB.

Example 1: Logical Indexing Using Single Condition

In this example, we first create logical indexing using the single condition and then create an array corresponding to that logical indexing.

A = magic(6); %Declare an array having size 6-by-6

B = A < 5; %Apply the logical condition

C = A(B) %Find the elements of A using logical indexing

Example 2: Logical Indexing Using Two or More Logical Conditions in MATLAB

This MATLAB code first creates an array of logical indexing using two conditional statements. After that, it creates another array C containing elements of array A that satisfy the logical indexing.

A = magic(6); %Declare an array having size 6-by-6

B = A > 15 & A <= 30; %Apply the logical conditions

C = A(B) %Find the elements of A using logical indexing

Conclusion


One of the approaches used to index the array elements is logical indexing. This approach allows us to create an array based on the logical conditions. When we apply the conditions, it extracts elements from the given array that satisfy the given logical conditions. This tutorial has provided an easy guide to implementing logical indexing in MATLAB. The examples provided are clear and easy to understand, allowing us to implement the concept in MATLAB.

About the author

Komal Batool Batool

I am passionate to research technologies and new ideas and that has brought me here to write for the LinuxHint. My major focus is to write on programming languages and computer science related topics.