I have a sparse array of tuples of positive real numbers (in fact a probability distribution) say
p=SparseArray[{{100,1}->0.25,{100,2}->0.25,{101,1}->0.3,{305,2}->0.2},{641601,2}]
Now I would like to sum every list on the first level to get a sparse array of form
psummed=SparseArray[{{100}->0.5,{101}->0.3,{305}->0.2},{641601}]
naturally I could do that by changing the heads of the sublists
psummed=Plus @@ # &/@ p;
However this changes the SparseArray to normal list and therefore takes too much time
AbsoluteTiming[res = Plus @@ # & /@ p;]
{1.0770617, Null}
Is there a nice and fast way how to do this, while the result will be still a SparseArray?
Using
Parton aSparseArrayobject extracts a sub-array in Sparse form, and adding Sparse arrays uses Sparse addition, therefore you can write:But wait, there's more! :o)
Because of the internal format of
SparseArrayyour original array will be much more efficiently stored if it is transposed. Compare:The tall skinny array takes up thousands of times as much space as the wide short one.
Further, with the data in this form we can do the sum more directly:
We can use
ArrayRulesto inspect the data:For other Mathematica questions I encourage you to join us on the dedicated site: