Friday, March 15, 2013

How to query select rows with logical indexing in Matlab/Octave

Once again, I am making this quick post because it took me a while to figure this out. Hopefully, this will save someone else some time (even if it's 30 seconds).

Let say you have the follow matrix

a = [1,2; 1,4; 2, 5; 2, 7]

or

a =

  1      2
  1      4
  2      5
  2      7

a > 4 will return a matrix with a 0 or 1 if the cell matches the condition. So in this case, it will return

  0      0
  0      0
  0      1
  0      1

The zeros represent the positions which are less than 4 and the ones are the positions that are greater than 4.

a(:,1) will return the first column of the matrix only

Basically, the line below will return only 2 and 4, since there are the only rows where the first position == 1

a1 = a(:,2)(a(:,1) ==1)

I know this is a sucky explanation but it's late and I'm tired.

No comments:

Post a Comment