sorting and counting

I have two arrays 'a' and 'b' of the same length and they may contain repeating numbers. I want to count how many number of pairs exist for a pair a(i),b(j). for e.g. a = [ 1 2 5 7] ; b = [ 9 9 3 4] ; then what I want is the following: (1,9) comes 2 times, (1,3) comes 1 time, (1,4) comes 1 time, (2,9) comes 2 times ......and so on. Can somebody please tell how can this be done ?

1 件のコメント

Karan
Karan 2012 年 4 月 7 日
Here is solution I am working on but doesnt seem to give the answer :
l=length(a);
i=1;j=1;
while i<(l+1);
while j<(l+1);;
if (b(i)==b(j) && a(i)==a(j));
m(i,j,i)=1;
else
end
j=j+1
end
i=i+1;
end
here, m is 3d ,matrix where for every pair obtained, it stores a value of 1 in one layer, and finally sum of 1 in each layer gives the number of pairs.
but this code is not working and I dont seem to find a flaw in it.
could somebody please tell the flaw, or an other way to do this problem ?

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

 採用された回答

Andrei Bobrov
Andrei Bobrov 2012 年 4 月 7 日

1 投票

a = [ 1 2 5 7] ; b = [ 9 9 3 4] ;
[aa bb] = ndgrid(a,b);
k = [aa(:) bb(:)];
[n1, n2, n2] = unique(k,'rows');
n3 = histc(n2,1:max(n2));
out = [n1, n3]

1 件のコメント

Karan
Karan 2012 年 4 月 7 日
bobrov you are simply amazing ... always glued to help others ... Thank you very much

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

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeShifting and Sorting Matrices についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by