7

I have matrix A in Matlab of dimension hxk and a matrix B of dimension yxk. I want to construct a vector C of dimension yx1 listing in each row j how many times B(j,:) appears in A.

Divakar
  • 218,885
  • 19
  • 262
  • 358
TEX
  • 2,249
  • 20
  • 43

3 Answers3

9

If you are looking for perfect matches, one solution with bsxfun -

C = squeeze(sum(all(bsxfun(@eq,A,permute(B,[3 2 1])),2),1))
Divakar
  • 218,885
  • 19
  • 262
  • 358
3

You can also use pdist2 (from the Statistics Toolbox):

C = sum(pdist2(A, B)==0);
Luis Mendo
  • 110,752
  • 13
  • 76
  • 147
2

Another solution using ismember and accumarray

A=[1 2 3; 4 5 6; 7 8 9; 1 2 3; 4 5 6; 10 11 12; 7 8 9];
B=[1 2 3; 10 11 12; 3 4 5; 7 8 9];
[uB,aB,cB]=unique(B,'rows');
[~,LocB] = ismember(A,uB,'rows');
C = accumarray(nonzeros(LocB),1,[size(B,1),1]);
C=C(cB);

which returns

C =

 2     1     0     2

or some crazy coding which seems to be faster for most instances:

[u,v,w]=unique([B;A],'rows');
wB=w(1:size(B,1));
wA=w(size(B,1)+1:end);
C=accumarray(wA,1,[numel(v),1]);
C=C(wB);
Daniel
  • 36,610
  • 3
  • 36
  • 69