create a sparse matrix 100x100 with 100 entries in python

To create a sparse matrix in Python, we can use the scipy.sparse module. Specifically, the csr_matrix function can be used to create a sparse matrix in the Compressed Sparse Row format.

Here's an example of creating a 100x100 sparse matrix with 100 random entries:

main.py
import numpy as np
from scipy.sparse import csr_matrix

# Generate random row and column indices
rows = np.random.randint(0, 100, size=100)
cols = np.random.randint(0, 100, size=100)

# Generate random data values
data = np.random.randn(100)

# Create the sparse matrix
sparse_matrix = csr_matrix((data, (rows, cols)), shape=(100, 100))

print(sparse_matrix.toarray())
369 chars
15 lines

Output:

main.py
[[ 0.          0.          0.          ...  0.         -1.19463097
   0.        ]
 [ 0.          0.          0.         ...  0.          0.
   0.        ]
 [ 0.          0.          0.          ... -0.88496577  0.
   0.        ]
 ...
 [ 0.          0.         -1.26095072 ...  0.          0.
   0.        ]
 [ 1.07212994  0.          0.         ...  0.          0.
   0.        ]
 [ 0.          0.          0.          ...  0.          0.
  -0.94315434]]
455 chars
14 lines

This creates a sparse matrix with 100 random, non-zero entries. The toarray() method is called at the end to convert the sparse matrix to a dense NumPy array for ease of viewing.

related categories

gistlibby LogSnag