[SciPy-user] sparse matrix multiplication elementwise ?

josef.pktd at gmail.com josef.pktd at gmail.com
Wed Apr 8 09:50:45 EDT 2009


On Wed, Apr 8, 2009 at 8:37 AM, Uwe Schmitt
<rocksportrocker at googlemail.com> wrote:
> I solved my question as follows:
>
>
> import numpy as np
> import scipy.sparse as sp
>
>
> def scale_sparse_matrix(A, by):
>
>    assert isinstance(A, sp.csr_matrix), "wrong format"
>
>    now = 0
>    for row in range(A.shape[0]):
>        upto = A.indptr[row+1]
>        while now < upto:
>            col = A.indices[now]
>            A.data[now] *= by[row, col]
>            now += 1
>
>
> if __name__ == "__main__":
>
>    A = np.zeros((3,4))
>    A[1,1] = 1
>    A[2] = 2
>
>    aa = sp.csr_matrix(A)
>    print "before:\n", aa
>
>    b = 2*np.ones_like(A)
>    scale_sparse_matrix(aa, by=b)
>
>    print "after:\n", aa
>
>
> On 8 Apr., 11:24, Uwe Schmitt <rocksportroc... at googlemail.com> wrote:
>> Hi,
>>
>> is there a way to multiply a sparse matrix with a dense numpy.array
>> elementwise ?
>>

I don't know if this is intended use, but it works. try this addition
to your example

if __name__ == "__main__":

   A = np.zeros((3,4))
   A[1,1] = 1
   A[2] = 2

   aa = sp.csr_matrix(A)
   print "before:\n", aa

   b = np.arange(12).reshape(3,4)      #2*np.ones_like(A)
   scale_sparse_matrix(aa, by=b)

   print "after:\n", aa

   # new version
   #multiply non-zero elements by corresponding elements of array b
   aa2 = sp.csr_matrix(A)
   aao=aa.tocoo()
   aa2.data *= b[aao.row,aao.col]
   print "new version:\n", aa2



More information about the SciPy-User mailing list