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

countmultiple criteria

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.

Best Answer

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