It appears that finding the cluster indices with Position
is extremely slow with large datasets, although the rest of the code is relatively fast. With thanks to ciaociao (see below), I've replaced it with a much faster construction.
I'd be interested to know if anybody can think of a more clever way of implementing the algorithm. Mathematica has the SparseArray
object, which is a good fit for the input and output configurations we are dealing with here, so one might consider using those from the beginning for the input. Thanks to ciaociao, who pointed out that one can extract the positions of non-zero elements easily from a SparseArray
with ["NonzeroElements"]
, we can restrict our attention to those only.