Reputation: 2728
Well I have an array called A
:
[8 2
6 1
6 1
6 1
1 2]
How to count the occurrence of the same rows? It does not work well with unique
because it does not differentiate between the rows.
Upvotes: 1
Views: 108
Reputation: 221564
One bsxfun
+unique
approach -
binmat1 = squeeze(all(bsxfun(@eq,A,permute(A,[3 2 1])),2))
[~,ind1] = unique(bi2de(binmat1),'stable')
uniqueA = A(ind1,:)
counts = sum(binmat1(ind1,:),2)
Thus, if you have A as:
A=[ 8 2;
6 1;
6 1;
6 1;
1 2;
63 1;
63 1]
Output would be:
uniqueA =
8 2
6 1
1 2
63 1
counts =
1
3
1
2
Upvotes: 0
Reputation: 112669
sparse
approach:
>> sparse(A(:,1), A(:,2), 1)
ans =
(6,1) 3
(1,2) 1
(8,2) 1
If you need it in the form of two variables as in Daniel's answer:
[ii jj Occurrences] = find(sparse(A(:,1), A(:,2), 1));
Rows = [ii jj];
which gives
Rows =
6 1
1 2
8 2
Occurrences =
3
1
1
Upvotes: 3
Reputation: 36710
Use unique
to get the indices.
[R,ixb,ix]=unique(A,'rows')
Then use histc
to count them
O=histc(ix,1:numel(ixb))
R contains the (unique) rows and O the number of occurrences.
Upvotes: 1