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.
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.
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.