MATLAB: How many times does each number appear

findhistograminterval countintervals

Let a
a =
1 4
3 5
4 7
6 8
be integer intervals
[1 2 3 4]
[3 4 5]
[4 5 6 7]
[6 7 8]
I'm looking for an output b to count the number of times each element appears. It is clear that 1 appears one time, 2 appears one time, 3 appears twice, and so on…
So the output b would list the element and how many times it appears:
b =
1 1
2 1
3 2
4 3
5 2
6 2
7 2
8 1
The challenge is, a is an extremely large nx2 array, so using find even with parallel looping is inefficient. Is there a fast way to yield b given a? If it helps, we can be sure that the elements down the left-hand column of a are sorted, but not necessarily so for the right-hand column. Thanks in advance!

Best Answer

Assuming that the second column of a is always >= the first column of a, then this is an efficient solution.
mA = max(a(:));
b = (1:mA)';
b = [b cumsum(accumarray(a(:,1),1,[mA 1]) + ...
accumarray(min(a(:,2)+1,mA),-1,[mA 1]))];
b(end) = b(end) +1;