[SciPy-User] numpy.diff of sparse matrix

Jonathan Stickel jjstickel@vcn....
Wed Sep 8 09:52:09 CDT 2010


I have found a workaround that meets my needs, in case anyone is interested:

In [37]: Is = sparse.identity(3)

In [38]: Ds = Is[1:] - Is[:-1]

In [39]: Ds.todense()
Out[39]:
matrix([[-1.,  1.,  0.],
         [ 0., -1.,  1.]])

I haven't yet tested for computational efficiency vs. dense matrices, 
but I suppose it should be good.

Jonathan


On 9/7/10 14:27 , Jason Rennie wrote:
> My experience is similar to yours---numpy doesn't work with scipy sparse
> matrices.  Not even numpy.dot does the right thing.  My guess is that
> you'd want to write the sparse diff for the sparse library.  An example
> of how to organize such function is the sparse hstack:
>
> http://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.hstack.html
>
> Cheers,
>
> Jason
>
> On Tue, Sep 7, 2010 at 2:49 PM, Jonathan Stickel <jjstickel@vcn.com
> <mailto:jjstickel@vcn.com>> wrote:
>
>     I'd like to use numpy.diff on a sparse matrix, but I get the following:
>
>
>     In [76]: np.diff(np.identity(3),axis=0)
>     Out[76]:
>     array([[-1.,  1.,  0.],
>             [ 0., -1.,  1.]])
>
>     In [77]: np.diff(sparse.identity(3),axis=0)
>     ---------------------------------------------------------------------------
>     IndexError                                Traceback (most recent
>     call last)
>
>     /Users/jstickel/temp/<ipython console> in <module>()
>
>     /opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/numpy/lib/function_base.pyc
>     in diff(a, n, axis)
>          961     slice1 = [slice(None)]*nd
>          962     slice2 = [slice(None)]*nd
>     --> 963     slice1[axis] = slice(1, None)
>          964     slice2[axis] = slice(None, -1)
>          965     slice1 = tuple(slice1)
>
>     IndexError: list assignment index out of range
>
>
>     I suppose numpy.diff doesn't know how to handle a sparse matrix object.
>       Converting to dense would work, but that would defeat the purpose of
>     using sparse matrices.  Any quick solutions?  I don't have time now, but
>     if I were to implement a sparse diff, should it go within numpy.diff or
>     be a separate function (maybe scipy.sparse.spdiff)?
>
>     Thanks,
>     Jonathan
>     _______________________________________________
>     SciPy-User mailing list
>     SciPy-User@scipy.org <mailto:SciPy-User@scipy.org>
>     http://mail.scipy.org/mailman/listinfo/scipy-user
>
>
>
>
> --
> Jason Rennie
> Research Scientist, ITA Software
> 617-714-2645
> http://www.itasoftware.com/
>
>
>
> _______________________________________________
> SciPy-User mailing list
> SciPy-User@scipy.org
> http://mail.scipy.org/mailman/listinfo/scipy-user


More information about the SciPy-User mailing list