create a sparse matrix 100x100 with 100 entries create a dense matrix 100x100 with 100 entries use sys.getsizeof to determine the sizes in python

To create a sparse matrix, we can use the scipy.sparse module. Specifically, we can create a sparse matrix of size 100x100 and fill it with 100 random entries using scipy.sparse.random. Here is the code:

main.py
import scipy.sparse
import numpy as np

sparse_matrix = scipy.sparse.random(100, 100, density=0.01, format="csr")
114 chars
5 lines

In this example, density specifies the fraction of non-zero entries in the matrix. You can adjust it to create more or fewer entries.

To create a dense matrix, we can use the numpy module. We can randomly generate a 100x100 array and then set all but 100 entries to 0. Here is the code:

main.py
dense_matrix = np.zeros((100, 100))
rows, cols = np.random.randint(0, 100, size=(2, 100))
dense_matrix[rows, cols] = np.random.random(100)
139 chars
4 lines

Finally, we can use the sys.getsizeof function to determine the sizes of these matrices in bytes:

main.py
import sys

sparse_size = sys.getsizeof(sparse_matrix)
dense_size = sys.getsizeof(dense_matrix)
print("Sparse matrix size:", sparse_size)
print("Dense matrix size:", dense_size)
178 chars
7 lines

The exact sizes will depend on your system, but the sparse matrix should be much smaller than the dense matrix, since it only stores non-zero values.

related categories

gistlibby LogSnag