MENU

A little magic called LOGICAL INDEXING

In MATLAB; row, column and linear indexing use integer indices.

While most MATLAB users are familiar with normal numerical indexing into vectors, matrices etc. MATLAB also provides a very efficient technique called logical indexing, where you use logical variables to index into data, extracting information that satisfies a condition. In this article, you will learn more about logical indexing.

Logical indexing eliminates the use of find function.

Numerical Indexing Example:
>> A = randi (10, 4, 5) %generate a matrix of random integers
A =
7     2     1     9     8
6     7     1     5     5
9     1     1     6    10
1     7     8     7     6
>> A_34 = A (3, 4) %Extract an element in row 3 and column 4
A_34 =
6
>> A_row2 = A (2,:) %Extract elements in row 2 and from column 1 to 5 (all columns)
A_row2 =
6     7     1     5     5

However, you can use logical variable as an array index, in which case MATLAB extracts the elements where the index is true, and this is called LOGICAL INDEXING.
Note: No need to use a find function if you not interested in the actual numerical indices.

 

 

 

 

For example:  – refer to variable A above
>> idx = A<5 %create logical variable matrix showing instant when a number in matrix A is less than 5. Where a condition is satisfied, there is a 1 and where it’s not satisfied there is a 0.
idx =
4×5 logical array
0   1   1   0   0
0   0   1   0   0
0   1   1   0   0
1   0   0   0   0

Now we can use idx to extract all the elements from A that satisfy the above condition.
>> num_lt5 = A(idx)
num_lt5 =

 

 

 

 

 

 

The output of num_lt5 give us all the number in A that are less than 5, going column by column and presenting them as a vector.
You can also use logical indexing to extract data from cell arrays, tables etc.
For example:
Names = {‘Jabu’, ‘Thando’, ‘Yolanda’, ‘Palesa’, ‘Mbali’}
Names =
1×5 cell array
{‘Jabu’}    {‘Thando’}    {‘Yolanda’}    {‘Palesa’}    {‘Mbali’}

>> indx = strcmp(Names, ‘Yolanda’) %strcmp function compares strings in Names with the “Yolanda’ and the output will be a logical array

 

 

 

What Can I Do Next?

Follow us

Twitter Page

LinkedIn Page

YouTube Channel