Use cut, awk and sort-bed to split the matrix into two separate and sorted BED files called A and B.
The second file B has the same genomic coordinates as the first file A, but contains an ID value constructed from the matrix file's second pair of columns.
It is necessary to sort both files, because their output is not in the correct sort order required for the next two steps.
Use bedops to merge 10-bp padded, neighboring regions around A, and then strip the 10 bp padding to create a new file called C. (Adjust this padding based on your criterion for neighboring regions.)
Use bedmap to map B onto C. Apply the --echo-map-id and --count operators to get the element IDs and number of elements from B which overlap elements in C.
$ cut -f1,2 foo.mtx | awk '{print $0"\t"($2+1)}' | sort-bed - > A
$ cut -f1-4 foo.mtx | awk '{print $1"\t"$2"\t"($2+1)"\t"$3":"$4}' | sort-bed - > B
$ bedops --merge --range 10 A | bedops --everything --range -10 - > C
$ bedmap --echo --echo-map-id --count C B > D
The file D contains your answer, though you might need to do a bit more post-processing on mapped elements per reference element, to get it into your exact desired format. You can use awk, Perl or whatever to process each line independently, at that point; no hash tables needed here.
I don't quite follow are you considering chr1 990, 1000 and 1010 as the same position in some sense?
I know it's not the same position but there are quite close to each other. I might rephrase the question by regrouping positions that are in the same region.