フィルターのクリア

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

4 ビュー (過去 30 日間)
wy6622
wy6622 2016 年 11 月 19 日
コメント済み: Star Strider 2016 年 11 月 19 日
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
  2 件のコメント
wy6622
wy6622 2016 年 11 月 19 日
Thank you!
Star Strider
Star Strider 2016 年 11 月 19 日
My pleasure!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by