sparse matrix representation python code example
Example 1: sparse matrix representation python use
import numpy as np
from scipy.sparse import csr_matrix
A = np.array([[1, 0, 0, 0, 0, 0], [0, 0, 2, 0, 0, 1],\
[0, 0, 0, 2, 0, 0]])
print("Dense matrix representation: \n", A)
S = csr_matrix(A)
print("Sparse matrix: \n",S)
B = S.todense()
print("Dense matrix: \n", B)
Example 2: how to convert a dense matrix into sparse matrix in python
from numpy import array
from scipy.sparse import csr_matrix
A = array([[1, 0, 0, 1, 0, 0], [0, 0, 2, 0, 0, 1], [0, 0, 0, 2, 0, 0]])
print(A)
S = csr_matrix(A)
print(S)
B = S.todense()
print(B)