Search code examples
pythonscipysparse-matrix

How to determine SciPy matrix "type" of a variable M


Is there a method or a reliable way to determine if a given matrix M was created via coo_matrix() or csc_matrix() / csr_matrix()?

How could I write a method like this:

MATRIX_TYPE_CSC = 1
MATRIX_TYPE_CSR = 2
MATRIX_TYPE_COO = 3
MATRIX_TYPE_BSR = 4
...

def getMatrixType(M):
    if ...:
         return MATRIX_TYPE_COO
    else if ...:
         return MATRIX_TYPE_CSR
    return ...

Thanks!


Solution

  • Assuming that your matrix is a sparse matrix, you want the .getformat() method:

    In [70]: s = scipy.sparse.coo_matrix([1,2,3])
    
    In [71]: s
    Out[71]: 
    <1x3 sparse matrix of type '<type 'numpy.int32'>'
        with 3 stored elements in COOrdinate format>
    
    In [72]: s.getformat()
    Out[72]: 'coo'
    
    In [73]: s = scipy.sparse.csr_matrix([1,2,3])
    
    In [74]: s
    Out[74]: 
    <1x3 sparse matrix of type '<type 'numpy.int32'>'
        with 3 stored elements in Compressed Sparse Row format>
    
    In [75]: s.getformat()
    Out[75]: 'csr'