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.py369 chars15 lines
Output:
main.py455 chars14 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.
gistlibby LogSnag