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
.
Asked
Active
Viewed 488 times
7
3 Answers
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
-
1@Shai Can't agree more really and makes it a one-liner! :) Appreciate the +1! – Divakar Aug 06 '14 at 13:26
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
-
-
1Hm. I just did some comparison with random data and I didn't get the same results as Luis and Divakar twice. There might be a bug somewhere... I'm just checking! – knedlsepp Mar 08 '15 at 20:59
-
Fails for non unique rows in B. I saw your incomplete and deleted answer to the other question, this "influenced" my thoughts ;) – Daniel Mar 08 '15 at 21:04
-
1
-
1
-
@Daniel: You could use `numel(u)` to omit `v` entirely. (Which might help to make the code more understandable) – knedlsepp Mar 08 '15 at 22:04
-
@knedlsepp: `numel(u)` is to large, might be replaced by `size(u,1)` which is identical to `numel(v)` – Daniel Mar 08 '15 at 22:53
-
Oh yeah, `size(.,1)` of course! But one could either omit `u` or `v` entirely as we only need the number of unique rows. – knedlsepp Mar 08 '15 at 22:54