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 Exchange에서 Shifting and Sorting Matrices에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by