How does logical indexing work ?
Show older comments
Was going through the MATLAB Getting Started course when I came across logical indexing.
>> v = v1(v1 > 6)
stores in v the elements of v1 that are greater than 6. Alright, I get that. But why ?
v1(1) should refer to the 1st element of v1, right ? How does MATLAB differentiate between the two ? Or am I going wrong somewhere and not understanding something ?
2 Comments
Bruno Luong
on 3 Oct 2018
MATLAB stores also the type of "number" (the correct term is CLASS); it the uses it to recognize when it logical (values from a boolean operation) or a real numbers (values from an arithmetic operation)
Adam
on 3 Oct 2018
Logical indexing is just a neat shortcut to avoid needing to use the 'find' function to create linear indices e.g.
v = v1( find( v1 > 6 ) )
would be equivalent and would be using linear indexing, but would be un-necessary as find is slow (relative to using logical indexing).
Accepted Answer
More Answers (1)
KALYAN ACHARJYA
on 3 Oct 2018
Edited: KALYAN ACHARJYA
on 3 Oct 2018
From the following example, you got the answer
v1=[1 2 3 4 5 6 7 8];
>> v=v1(v1>6)
v =
7 8
When linear indexing v1(1 up to the length of the v1)
Here v1 is variable name its v1(1) first element, v1(2) second element...elementwise
_ stores in v the elements of v1 that are greater than 6. Alright, I get that. But why ?_
here Matlab check the v1 in element wise,v only allows the v1 element values having greater than 6.
Always recomended to use Logical indexing for neat code and easily debug the code
Hope this help you!
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!