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

5 次查看(过去 30 天)
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 个评论
wy6622
wy6622 2016-11-19
编辑:wy6622 2016-11-19
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?

请先登录,再进行评论。

采纳的回答

Star Strider
Star Strider 2016-11-19
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

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Get Started with MATLAB 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by