The goal is to assemble a SparseArray
in an additive fashion.
Let us assume we have a large List
of indices (some will be repeated). We generate a simple test list of indices and values
ind = RandomInteger[{1, 4}, {10, 2}];
val = RandomReal[{-1,1}, Length[ind]];
where each value corresponds to an index from ind
. I would like to build a SparseArray
in a way such that the repeated index values are summed into the array.
If we simply use:
SparseArray[ind -> val, {4,4}]
only the first index encounter is written into the SparseArray
, all repeated indices are ignored.
Current Solution (slow + ugly)
This solution is slow and is only shown to make precise what exactly I am trying to accomplish. We pre-allocate a sparse array of the correct size and use Do
to accumulate the values at each index:
n = 5;
ind = RandomInteger[{1, n}, {3*n, 2}];
val = RandomReal[{1, 1}, Length[ind]];
A = SparseArray[{1, 1} -> 0, {n, n}];
Do[
A[[Sequence @@ ind[[i]]]] += val[[i]]
,{i, 1, Length[val]}
]
There are some great tips on working with SparseArrays
in Efficient by-element updates to SparseArrays and SparseArray row operations. A clever combination of GatherBy
, Sort
, etc. operations on ind
and val
may be good path to head down. I just can't see it yet.