Selecting only a specific number of rows fulfilling a condition

Ruun picture Ruun · Nov 13, 2011 · Viewed 31.4k times · Source

I currently started to work with octave for some data analysis and have some problems for a specific matrix manipulation.

Assume you have the following data matrix:


    A =

        1   11   22   33
       44   13   12   33
        1   14   33   44

Now I would like to delete all rows of this matrix which don't accomplish e.g. the following condition.


    octave:6> A(:, 4) == 33
    ans =

       1
       1
       0

And I'll get the matrix of this form which only selects these rows:


    A_new =

        1   11   22   33
       44   13   12   33

I know this is possible with the help of some loops. But is there maybe a cleaner solution e.g. by using the provided standard library? That would be great :]

Some similar question was also already posted for R: In R, select rows of a matrix that meet a condition

Answer

Amro picture Amro · Nov 13, 2011

Try:

A = [
    1   11   22   33
    44  13   12   33
    1   14   33   44
];
idx = ( A(:,4)==33 );
A_new = A(idx,:)

This is using logical indexing