MATLAB: Sorting and counting

countsort

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 ?

Best Answer

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]