Kareem Ergawy
Kareem Ergawy

Reputation: 677

Rowwise 2 dimensional matrix intersection in Matlab

I will try to explain what I need through an example.

Suppose you have a matrix x as follows:

1 2 3
4 5 6

And another matrix y as follows:

1 4 5
7 4 8

What I need is (without looping over the rows) to perform an intersection between each 2 corresponding rows in x & y. So I wish to get a matrix z as follows:

1
4

The 1st rows in x and y only have 1 as the common value. The 2nd rows have 4 as the common value.

EDIT: I forgot to add that in my case, it is guaranteed that the intersection results will have the same length and the length is always 1 actually.

Upvotes: 1

Views: 221

Answers (2)

Divakar
Divakar

Reputation: 221584

I am thinking bsxfun -

y(squeeze(any(bsxfun(@eq,x,permute(y,[1 3 2])),2)))

Sample runs -

Run #1:

>> x
x =
     1     2     3
     4     5     6
>> y
y =
     1     4     5
     7     4     8
>> y(squeeze(any(bsxfun(@eq,x,permute(y,[1 3 2])),2)))
ans =
     1
     4

Run #2:

>> x
x =
     3     5     7     9
     2     7     9     0
>> y
y =
     6     4     3
     6     0     2
>> y(squeeze(any(bsxfun(@eq,x,permute(y,[1 3 2])),2)))
ans =
     0
     3
     2

Upvotes: 4

user2271770
user2271770

Reputation:

The idea is to put the matrices together and to look for duplicates in the rows. One idea to find duplicated numeric values is to diff them; the duplicates will be marked by the value 0 in result.

Which leads to:

%'Initial data'
A = [1 2 3; 8 5 6];
B = [1 4 5; 7 4 8]; 

%'Look in merged data'
V = sort([A,B],2);      %'Sort matrix values in rows'
R = V(diff(V,1,2)==0);  %'Find duplicates in rows'

This should work with any number of matrices that can be concatenated horizontally. It will detect all the duplicates, but it will return a column the same size as the number of rows only if there is one and only one duplicate per row in the matrices.

Upvotes: 0

Related Questions