+4 votes
in Programming Languages by (14.3k points)
I have 2 large CSR matrices. How can I check whether those matrices are the same or different?

1 Answer

0 votes
by (24.7k points)

If you have 2 CSR matrices (X and Y) of different shapes, you can simply use X!=Y and it will return True.

If CSR matrices are of the same shape, X!=Y returns a matrix of the same shape with boolean elements. You can then use numpy.where() to check whether they are the same or different.

Here is an example with 3 matrices A, B, and C of the shape 4x4:

import numpy as np
from scipy.sparse import csr_matrix

def comare_csr_matrix(x, y):
    if np.sum(x != y) == 0:
        return 'Same Matrices'
        return 'Different Matrices'

if __name__ == "__main__":
    row = np.array([0, 0, 1, 1, 2, 3, 3])
    col = np.array([0, 3, 0, 2, 1, 2, 3])
    data = np.array([1 for i in range(len(col))])
    data1 = np.array([2 for i in range(len(col))])
    A = csr_matrix((data, (row, col)), shape=(4, 4))
    B = csr_matrix((data, (row, col)), shape=(4, 4))
    C = csr_matrix((data1, (row, col)), shape=(4, 4))
    print(comare_csr_matrix(A, B))
    print(comare_csr_matrix(B, C))