Re: incrementing elements of a SparseArray
- To: mathgroup at smc.vnet.net
- Subject: [mg123701] Re: incrementing elements of a SparseArray
- From: Leonid Shifrin <lshifr at gmail.com>
- Date: Fri, 16 Dec 2011 05:44:58 -0500 (EST)
- Delivered-to: l-mathgroup@mail-archive0.wolfram.com
- References: <201112150955.EAA22977@smc.vnet.net>
Why don't you assign your original SparseArray to a symbol/variable (say s), and then increment that variable, properly indexed (e.g. s[[1,1]]++). Note however that this will be efficient only if you end up with not too many incremented elements, due to the way SparseArray is implemented (it uses packed arrays to store positions of non-zero elements, and every time you convert some element from zero to non-zero, that packed array has to be modified (recreated)). But if you final array will be mostly zeros, then no need to worry. Regards, Leonid On Thu, Dec 15, 2011 at 12:55 PM, Matt Enlow <mattenlow at gmail.com> wrote: > Hi, > > I am creating a very large 2-dimensional SparseArray ("M") by starting with > an empty one (all zeros) and iterating a tight loop, which increments a > different element of M each time. In the end result, M will still be mostly > zeros, but some entries will be anywhere from 1 to about 50. I have a way > to do it, but I feel as though there is probably a better way. > > Originally I thought I could use MapAt, but when I use it on a SparseArray, > it returns a "Normal" array, which I don't want to keep having to convert > back to a SparseArray every time. My "fix" was to create a new SparseArray > that only has a 1 in the position I want to increment (zeros everywhere > else), then add it to M. Again, this works, but feels inefficient. Is there > a simpler and/or more efficient way to do this? > > Thanks in advance, > > Matt Enlow >
- References:
- incrementing elements of a SparseArray
- From: Matt Enlow <mattenlow@gmail.com>
- incrementing elements of a SparseArray