farzin parsa
farzin parsa

Reputation: 547

how to find indices based on equality of some cols with a set (Query on matrix) in Matlab

I have a matrix with n rows and 3 columns. lets call it A=[23 45 6;32 4 78;67 5 34; 54 1 4;6 9 2]

Now I have a set of points: B={ P1=[X1,Y1] P2=[X2,Y2] ... }= { [6 9] [32 4] }

I want to set a query on matrix A so that it returns me the index of the rows(i) in which for all set B:

Pk(1,1) ( or Xk) == A(i,1) && Pk(1,2) ( or Yk) == A(i,2) 

In other words,set the query based on column 1 && 2 over A and compared them with B, so the output is the index of rows that has same values in col 1 and 2 with the Xk,Yk in B:

output: 5,2

Upvotes: 0

Views: 109

Answers (2)

Dan
Dan

Reputation: 45752

Make B a matrix as suggested by @TJ1

B=[6 9; 32 4];

Just use intersect with the rows options (and the second output)

[~, i, ~] = intersect(A(:, 1:2), B, 'rows')

I have indexed on the first 2 columns from A because you are only interested in those columns and obviously intersect wants the two matrices to have the same number of columns.

The result:

i =

     5
     2

Upvotes: 2

TJ1
TJ1

Reputation: 8488

Place B in a matrix format as well, for example:

B=[6 9; 32 4];

Here is a MATLAB code that you can use to do this:

 k=0;
 output=[];
 for n=1:5
   for m=1:2 
     if (sum(A(n,1:2)==B(m,:)) == 2)
       k = k +1;
       output(k) = n;
     end
    end
  end

your result is in output.


EDIT:

I'm adding an explanation of the line (sum(A(n,1:2)==B(m,:)) == 2). Lets look at it piece by piece. A(n, 1:2) gives us a 1x2 vector which is the first two columns of the nth row of A. B(m,:) is also a 1x2 vector as B only has two columns. So let's say that we now have [6 9] from the last row of A and [6 9] from the first row of B.

Try [6 9] == [6 9] in the command line. The result is a logical vector: [1 1]. The reason is that == will compare the vectors element by element. So the first 1 is because 6 equals 6 and the second tells us the 9s are equal. If you try [6 9] == [7 9] you'll get [0 1] because the first elements are now different.

Thus to assess if BOTH elements are the same we expect the sum of the vector that results from the == operator to equal two. If it equals 1 then only one element was the same, we need it to be 2 to say the whole vector is equal (2 because the vectors only have 2 elements). So sum([6 9] == [6 9]) gives 2 but sum([7 9] == [6 9]) only gives 1.

Hence the condition to test for the equality of a row is if (sum(A(n,1:2)==B(m,:)) == 2)

Upvotes: 1

Related Questions