Search code examples
numpymatrixsparse-matrix

Commute numpy sparse matrix dot product


To my understanding, numpy.sparse.csr_sparse.dot(other) does multiply other to my sparse matrix from the right:

A = numpy.sparse.csr_sparse(something)
B = numpy.matrix(something)
C = A.dot(B)                     # C = A*B

How do I commute the two matrices to get B*A without losing the benefits of saving my matrix as a sparse one (i.e. .todense() etc.)?


Solution

  • A little refresher of matrix multiplication properties:

    D = B * A
    D.T = A.T * B.T
    D = (A.T * B.T).T
    

    Which then leads to the obvious:

    D = A.T.dot(B.T).T
    

    Note that transposition of CSR and CSC matrices is very fast, as it simply changes the shape and the type (from CSR to CSC, or from CSC to CSR), leaving the internal data unchanged.