Answers for "sparse matrix to array"

1

sparse matrix representation python use

import numpy as np
from scipy.sparse import csr_matrix

# create a 2-D representation of the 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)

# convert to sparse matrix representation 
S = csr_matrix(A)
print("Sparse matrix: n",S)

# convert back to 2-D representation of the matrix
B = S.todense()
print("Dense matrix: n", B)
Posted by: Guest on January-01-2021
0

how to convert a dense matrix into sparse matrix in python

# dense to sparse
from numpy import array
from scipy.sparse import csr_matrix
# create dense matrix
A = array([[1, 0, 0, 1, 0, 0], [0, 0, 2, 0, 0, 1], [0, 0, 0, 2, 0, 0]])
print(A)
# convert to sparse matrix (CSR method)
S = csr_matrix(A)
print(S)
# reconstruct dense matrix
B = S.todense()
print(B)
Posted by: Guest on March-10-2021

Python Answers by Framework

Browse Popular Code Answers by Language