[SciPy-user] sparse matrix multiplication elementwise ?

Uwe Schmitt rocksportrocker@googlemail....
Wed Apr 8 07:37:27 CDT 2009


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...@googlemail.com> wrote:
> Hi,
>
> is there a way to multiply a sparse matrix with a dense numpy.array
> elementwise ?
>
> Greetings, Uwe
> _______________________________________________
> SciPy-user mailing list
> SciPy-u...@scipy.orghttp://mail.scipy.org/mailman/listinfo/scipy-user


More information about the SciPy-user mailing list