Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scipy sparse matrix multiplication

I have this example of matrix by matrix multiplication using numpy arrays:

import numpy as np
m = np.array([[1,2,3],[4,5,6],[7,8,9]])
c = np.array([0,1,2])
m * c
array([[ 0,  2,  6],
       [ 0,  5, 12],
       [ 0,  8, 18]])

How can i do the same thing if m is scipy sparse CSR matrix? This gives dimension mismatch:

sp.sparse.csr_matrix(m)*sp.sparse.csr_matrix(c)
like image 530
Antonio Simunovic Avatar asked Mar 01 '17 17:03

Antonio Simunovic


People also ask

How do you multiply a sparse matrix?

To Multiply the matrices, we first calculate transpose of the second matrix to simplify our comparisons and maintain the sorted order. So, the resultant matrix is obtained by traversing through the entire length of both matrices and summing the appropriate multiplied values.

What does Scipy sparse Csr_matrix do?

Returns a copy of column i of the matrix, as a (m x 1) CSR matrix (column vector). Format of a matrix representation as a string. Maximum number of elements to display when printed. Number of stored values, including explicit zeros.

What is Densematrix?

A dense matrix is created by calling the function matrix . The arguments specify the values of the coefficients, the dimensions, and the type (integer, double, or complex) of the matrix. cvxopt. matrix(x[, size[, tc]]) size is a tuple of length two with the matrix dimensions.


1 Answers

You can call the multiply method of csr_matrix to do pointwise multiplication.

sparse.csr_matrix(m).multiply(sparse.csr_matrix(c)).todense()

# matrix([[ 0,  2,  6],
#         [ 0,  5, 12],
#         [ 0,  8, 18]], dtype=int64)
like image 127
Elliot Avatar answered Sep 20 '22 15:09

Elliot