3

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!

Fraukje
  • 673
  • 3
  • 20

1 Answers1

5

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:

enter image description here

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:

enter image description here

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!

Dan
  • 45,079
  • 17
  • 88
  • 157
  • Cool, yeah I knew about the `fix` button, but nice to know that this functionality is called mlint. Odd detail: the example you put up there didn't produce any mlint for me (although it obviously should)... – Fraukje Aug 16 '13 at 10:01