Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter Matrix by some column value

Tags:

matrix

matlab

Consider I have this Matrix:

   02, 04, 06, 08, 10, 2
   07, 14, 21, 28, 35, 2
   11, 22, 33, 44, 55, 0
   15, 14, 21, 28, 35, 2

I would like to have the same matrix but with only rows with last column = 2. So I want this Matrix:

   02, 04, 06, 08, 10, 2
   07, 14, 21, 28, 35, 2
   15, 14, 21, 28, 35, 2

I could parse all matrix, but is there any other way?

Edit

To be more precise I have a cell array with strings:

   02, 04, Some String, 08, 10, 2
   07, 14, Some String1, 28, 35, 2
   11, 22, Some String1, 44, 55, 0
   15, 14, Some String, 28, 35, 2
like image 767
dynamic Avatar asked Jan 15 '13 15:01

dynamic


1 Answers

Just use logical indexing on the rows of your matrix:

row_idx = (A(:, end) == 2);

Now row_idx contains a logical array of 1s and 0s, with 1s where the last element of the row equals 2.

Now filter these rows with:

A_filtered = A(row_idx, :);

All these steps are usually performed in a one-liner:

A_filtered = A(A(:, end) == 2, :);
like image 119
Eitan T Avatar answered Oct 21 '22 12:10

Eitan T