Use logical indexing instead of FIND

淺唱寂寞╮ 提交于 2019-12-23 16:10:38

问题


Within a loop in my code I use a one-liner to find and plot the minimum of some potential (for clarity: the 7 corresponds to the cells containing the potential values, the 5 to the x-values):

plot(PDdata{subject,5}{1,1}(find(PDdata{subject,7}==...
    min(PDdata{subject,7}))),min(PDdata{subject,7}),'ko')

Now Matlab suggests to use logical indexing instead of FIND and although I've looked into it only briefly, it doesn't strike me as something I should do here. Main question here is thus whether I should employ logical indexing (I prefer to keep it a one-liner!), and if so: how?

I apologize in advance for asking such a minor question, but I'm trying to increase my Matlab knowledge so hopefully a short answer would help me out already!


回答1:


Dennis is correct in the comment. The idea is that using logical indexing directly cuts out a step. So if you're trying to extract all the elements in a matrix that are greater than 2 for example, using find you would do this:

A = [1 3 2 1 4 1]
A(find(A>2))

which becomes something like

A(find([0 1 0 0 1 0]))

then

A([2, 5])

and finally

[3, 4]

However if you used logical indexing directly like this:

A(A>2)

You get

A([0 0 1 0 0 1 0])

and finally

[3,4]

So you get exactly the same result, and you skip a call to find which as you can see is completely extraneous in these cases.

Then just to add something pretty cool, unless your Matlab is pretty old, the mlint (the bit that gives you that warning) can actually fix this for you. If you hover over the find which is underlined in red you get this:

So this is a basic version of exactly that mistake, see at the end there is a little fix button. This is what you get after clicking it:

OK so in this instance it's normal indexing instead of logical but the point remains, mlint can fix this for you which is pretty awesome!



来源:https://stackoverflow.com/questions/18268966/use-logical-indexing-instead-of-find

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!