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