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 Kommentar

Karan
Karan am 7 Apr. 2012
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 ?

Melden Sie sich an, um zu kommentieren.

 Akzeptierte Antwort

Andrei Bobrov
Andrei Bobrov am 7 Apr. 2012

1 Stimme

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 Kommentar

Karan
Karan am 7 Apr. 2012
bobrov you are simply amazing ... always glued to help others ... Thank you very much

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by