user3545355
user3545355

Reputation: 23

How to extract rows of a matrix with condition in matlab

Suppose

  A =  1  0  0
       1  0  1
       0  0  1
       1  0  1
       0  0  0

Now I want to extract rows whose 1st and 3rd column values are 1 at the same row ie output should be

    1  0  1
    1  0  1

tried with A(A(1:end,1)==A(1:end,3)==1), but not getting result.

Upvotes: 2

Views: 1057

Answers (3)

Rody Oldenhuis
Rody Oldenhuis

Reputation: 38052

If you know for sure that A is logical, or will only contain 0's and 1's, then

A(A(:,3) & A(:,1), :)

otherwise, you need an explicit comparison to 1, so then go with Rafael's solution.

The reason why chaining doesn't work (your initial attempt) is the following. Consider the first part:

>> ( A(1:end,1)==A(1:end,3) )
ans =
     0
     1
     0
     1
     1

Comparing this to 1 will obviously give the same result:

>> ( A(1:end,1)==A(1:end,3) ) == 1
ans =
     0
     1
     0
     1
     1

e.g., you're not comparing the values to 1, but comparing the result of the comparison to 1. Note that order is irrelevant:

>> 1 == A(1:end,1) == A(1:end,3) 
ans =
     0
     1
     0
     1
     1

>> A(1:end,1) == 1 == A(1:end,3) 
ans =
     0
     1
     0
     1
     1

Upvotes: 0

Divakar
Divakar

Reputation: 221754

Maybe a better example -

A = [
    1  1  0
    1  0  1
    0  0  1
    1  0  1
    0  0  0]

You can achieve your result using ismember -

out = A(ismember(A(:,[1 3]),[1  1],'rows'),:)

Output -

out =

     1     1     1
     1     0     1
     1     0     1

Extended Part: If you want to extend this to a bigger case, let's say a case with A as 10x10 and you would like to extract all rows with ones on 1, 3, 6, 8 and 9 column numbers, so just do this -

out = A(ismember(A(:,[1 3 6 8 9]),ones(1,5),'rows'),:)

Upvotes: 0

Rafael Monteiro
Rafael Monteiro

Reputation: 4549

Try this:

A(A(:,1) == 1 & A(:,3) == 1, :)

Upvotes: 3

Related Questions