Sparse Matrices
Dense Matrices
A matrix is called dense if it has non-zero entries. For example:
To store the matrix, all components are saved in row-major order. For given above, we would store:
The dimensions of the matrix are stored separately.
Sparse Matrices
A matrix is called sparse if it has non-zero entries. For example:
COO (Coordinate Format) stores arrays of row indices, column indices and the corresponding non-zero data values in any order. This format provides fast methods to construct sparse matrices and convert to different sparse formats. For the COO format is:
How to interpret: The first entries of , , are 12.0, 4, 4, respectively, meaning there is a 12.0 at position (4, 4) of the matrix; second entries are 9.0, 2, 4, so there is a 9.0 at (2, 4).
CSR (Compressed Sparse Row) encodes rows offsets, column indices and the corresponding non-zero data values. This format provides fast arithmetic operations between sparse matrices, and fast matrix vector product. The row offsets are defined by the followign recursive relationship (starting with ):
where is the number of non-zero elements in the row. Note that the length of is , where the last element in is the number of nonzeros in . For the CSR format is:
How to interpret: The first two entries of gives us the elements in the first row. Interval [0, 2) of and , corresponding to two (data, column) pairs: (1.0, 0) and (2.0, 3), means the first row has 1.0 at column 0 and 2.0 at column 3. The second and third entries of tells us [2, 5) of and corresponds to the second row. The three pairs (3.0, 0), (4.0, 1), (5.0, 3) means in the second row, there is a 3.0 at column 0, a 4.0 at column 1, and a 5.0 at column 3.
CSR Matrix Vector Product Algorithm
The following code snippet performs CSR matrix vector product for square matrices:
import numpy as np
def csr_mat_vec(A, x):
Ax = np.zeros_like(x)
for i in range(x.shape[0]):
for k in range(A.rowptr[i], A.rowptr[i+1]):
Ax[i] += A.data[k]*x[A.col[k]]
return Ax
Review Questions
- See this review link
ChangeLog
- 2022-03-06 Victor Zhao chenyan4@illinois.edu: Added instructions on how to interpret COO and CSR
- 2020-03-01 Peter Sentz: extracted material from previous reference pages