Clear Filters
Clear Filters

How to count the number of times a pair of values occurs in an N by 2 matrix?

7 views (last 30 days)
I have 2 vectors A and B consisting of 1 and 2 and I'd like to count the number of times each pair (1,1), (1,2), (2,1) and (2,2) occurs.
I tried the following A = [ 1 2 2 1 1 ]'; B = [ 2 2 1 2 1 ]'; C = [A , B]; x = [1 1; 1 2; 2 1; 2 2]; count = zeros(4,1); for k = 1:4 count(k) = sum(C==x(k,:)); end
It returns an error saying dimensions don't match. The code works if C is one-dimensional, for example: C = [ 1 2 2 1 1 ]'; x = [1 ; 2]; count = zeros(2,1); for k = 1:2 count(k) = sum(C==x(k)); end
Why does it not work if C is now 2 columns and I'm asking if a particular row is equal to a row of x?
Can you suggest a fix? Thank you.
  1 Comment
wy6622
wy6622 on 19 Nov 2016
Edited: wy6622 on 19 Nov 2016
UPDATE:
This works c = accumarray([A(:), B(:)],1);
c(1,1);
c(1,2);
c(2,1);
C(2,2);
I'm guessing the == only works for scalars?

Sign in to comment.

Accepted Answer

Star Strider
Star Strider on 19 Nov 2016
See if this does what you want:
A = [ 1 2 2 1 1 ]';
B = [ 2 2 1 2 1 ]';
C = [A , B];
[Cu,~,ic] = unique(C, 'rows');
count_mtx = accumarray(ic,1);
fprintf(1, '\t Pair\t Count\n')
fprintf(1, '\t%d\t%d\t\t%d\n', [Cu count_mtx]')
Pair Count
1 1 1
1 2 2
2 1 1
2 2 1

More Answers (0)

Categories

Find more on Get Started with MATLAB in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!