SciPy — Sparse Matrices
What are sparse matrices?
Matrices where most elements are zero, stored efficiently.
Create sparse matrix
from scipy.sparse import csr_matrix
import numpy as np
dense = np.array([[1, 0, 0], [0, 0, 3], [0, 4, 0]])
sparse = csr_matrix(dense)
print(f"Dense: {dense.nbytes} bytes")
print(f"Sparse: {sparse.data.nbytes} bytes")
COO format
from scipy.sparse import coo_matrix
row = np.array([0, 1, 2])
col = np.array([0, 2, 1])
data = np.array([1, 3, 4])
sparse = coo_matrix((data, (row, col)), shape=(3, 3))
print(sparse.toarray())
Operations
from scipy.sparse import csr_matrix
import numpy as np
A = csr_matrix(np.array([[1, 2], [3, 4]]))
B = csr_matrix(np.array([[5, 6], [7, 8]]))
# Matrix multiplication
C = A @ B
print(f"A * B:\n{C.toarray()}")
# Transpose
AT = A.T
print(f"A^T:\n{AT.toarray()}")
Solving sparse systems
from scipy.sparse.linalg import spsolve
import numpy as np
from scipy.sparse import csr_matrix
A = csr_matrix(np.array([[4, 1], [1, 3]]))
b = np.array([1, 2])
x = spsolve(A, b)
print(f"Solution: {x}")
Sparse eigenvalues
from scipy.sparse.linalg import eigsh
import numpy as np
from scipy.sparse import random
A = random(100, 100, density=0.1, format='csr')
eigenvalues, eigenvectors = eigsh(A, k=5)
print(f"Top 5 eigenvalues: {eigenvalues}")
Conversion
# To dense
dense = sparse.toarray()
# From dense
sparse = csr_matrix(dense)
# Change format
csc = sparse.tocsc()
lil = sparse.tolil()
Mini Practice
- Create sparse matrices
- Perform matrix operations
- Solve sparse systems
- Find eigenvalues
Up Next
Continue with Special Functions - Mathematical functions.
Related Topics
Frequently Asked Questions about Sparse Matrices
What is Sparse Matrices in SciPy?
Sparse Matrices is a fundamental concept in SciPy. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Sparse Matrices?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Sparse Matrices.
Why is Sparse Matrices important in SciPy?
Sparse Matrices is essential for SciPy development. Understanding this concept will help you write better code and solve real-world problems more effectively.