Finding common elements in two matrices of different lengths

29 views (last 30 days)
Greetings, I’ve a question about comparing matrices 'a' and 'b' then creating a third matrix 'c' based on matching pairs of numbers in two other matrices. Current example:
a = [17,9;23,3;24,3;23,3;24,3;9,6;10,6;23,3;24,3;23,3]
b = [17,1;18,1;21,1;23,3;24,3;23,4;24,4;9,6;10,6;14,12;23,12;24,12;23,14]
My goal is to create 'c' where both columns in 'a' and 'b' are the same. So, row 1 of 'a' would be excluded, as would the first 2 rows of 'b', etc. etc.. Any help with accomplishing this task would be greatly appreciated.
Cheers, Jason

Accepted Answer

Walter Roberson
Walter Roberson on 10 May 2018
It is not clear what output you want, considering you have two inputs. Perhaps
c = intersect(a,b,'rows');
or
c = [ismember(a,b,'rows'); ismember(b,a,'rows')];
  1 Comment
Jason
Jason on 11 May 2018
Hi Walter,
Thanks for the answers, both of them work (see below). However, intersect turned out to be the more elegant answer. My goal is to create c from the common rows of a and b.
Option #1
c = find(ismember(a,b,'rows'))
d = [];
for i=1:numel(c)
d(i,:) = a(c(i),:)
end
Option #2
c = intersect(a, b, 'rows', 'stable');
Thanks again for pointing me in the right direction.
Cheers, Jason

Sign in to comment.

More Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!