How does logical indexing work ?
显示 更早的评论
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 个评论
Bruno Luong
2018-10-3
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
2018-10-3
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).
采纳的回答
更多回答(1 个)
KALYAN ACHARJYA
2018-10-3
编辑:KALYAN ACHARJYA
2018-10-3
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!
类别
在 帮助中心 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!