Logical Indexing in MATLAB
MATLAB is an industry standard programming package for the collection, exploration and display of technical and scientific data. MATLAB code is optimized for operations on matrices, multidimensional collections of data. For ease of use, MATLAB provides a variety of ways to access elements within an array, including indexing by using logical or boolean values.
-
Logical Values
-
A logical or boolean variable can have only the values true or false. It can most efficiently be represented by a single bit, with the value of 0 corresponding to false and the value of 1 corresponding to true. More commonly, a value of exactly 0 corresponds to false while any nonzero value can correspond to true. It is possible to treat any numerical array as a logical variable in MATLAB.
Logical Array Indexing
-
In MATLAB, a logical array of equal extent can be used as the index to select elements from an array.
result = some_array(logical_array)
The result would be a column vector containing the values of some_array at the indices where logical_array was true or 1. In some cases, you may wish to leave the structure of some_array intact, instead setting to zero all values that are false int he logical array.
another_result = some_array .* logical array
The another_result would be equal in extent to some_array. The ".*" operator is for element-wise multiplication of matrices.
Logical Operations on Arrays
-
Before using logical array indexing, it is necessary to first construct an appropriate logical array. In MATLAB, normal boolean operators can be used on matrices as well.
my_matrix > 5
my_matrix == 10
my_matrix <= 3
my_matrix != 15A logical array can also be constructed using the logical() function, setting the appropriate dimensions. The values can then be set through a variety of operations for more complex tasks.
Find Function
-
Logical indexing returns an ordered vector of the values in the matrix at points where the logical index is true. However, the position may not be known. The find() function returns the index of logically true values. The results of the find() function can be critical in interpreting the results of logical indexing
locations = find(logical_index)
locations = find(my_matrix > 5)
-
Related Searches
References
- Photo Credit Ablestock.com/AbleStock.com/Getty Images