1

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.

2
  • Could you give the expected output for this example? Obviously Divakar understood your question in a different way than I did. Commented May 16, 2014 at 20:06
  • @Daniel Guess I was mistaken, so had to change my codes. Commented May 16, 2014 at 21:13

3 Answers 3

3

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
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.