TL;DR
A matrix is a grid of numbers (see Matrix Multiplication for how they combine). Most grids that come from real problems are mostly zeros: a friendship table where each person knows a few hundred of a billion people, or a finite-difference grid (a way of approximating a physical quantity on evenly spaced points) where each point touches only its neighbours. A sparse matrix is a grid like that. Instead of storing every cell, you store only the nonzero cells, each with its position, and treat everything else as zero.
This saves memory, and it saves time, because a multiplication only has to touch the entries that are not zero. The saving can be a factor of a thousand or more.
Where you'll see it: in the link graphs behind web search (see PageRank), in the matrices that describe a road network or a social network, in the large linear systems solved when simulating heat, fluid flow or structures, and in the weights of very large recommender models.
Intuition
Start with a friendship table
Imagine a table for a thousand people, with one row and one column per person, and a mark in the cell where two people are friends. Most people know only a handful of others, so almost every cell is blank. Writing out a full grid of a million cells, nearly all of them blank, wastes almost all of the paper. A better record is a list: "Ana knows Ben, Ben knows Ana, Ben knows Chen, ..." That list is the same information in a fraction of the space. A sparse matrix is that list, arranged so that a computer can still do arithmetic on it quickly.
Why the zeros are the expensive part
A dense matrix is stored in full, so a grid takes a million numbers whether they are zero or not. Multiplying it by a Vector takes a million multiplications. If only three numbers per row are nonzero, the same job needs about three thousand multiplications, because multiplying by zero contributes nothing. The work and the memory both follow the number of nonzeros, not the size of the grid.
flowchart LR A[Full grid: n by n cells] --> B[Mostly zeros] B --> C[Store only nonzero entries] C --> D[Memory and work scale with nonzeros]
The math
Definition
A matrix with rows and columns is sparse when the number of nonzero entries, written , is much smaller than . There is no exact cut-off. What matters is that is small enough that skipping the zeros changes the cost by a large factor.
Here and are the number of rows and columns, and is the count of entries that are not zero. The ratio is the density. A matrix with density 0.001 has only one nonzero in every thousand cells.
Storage
A common format is compressed sparse row (CSR). It keeps three arrays:
values: the nonzero numbers, row by row.col_index: the column of each stored value, in the same order.row_ptr: for each row, the position invalueswhere that row starts. It has one more entry than there are rows, so that the last row's end is also recorded.
To find row , read the values from row_ptr[i] up to, but not including, row_ptr[i+1]. Each stored value carries its column, so the computer knows where it goes. Other formats such as coordinate lists (one triple of row, column and value per nonzero) and dictionary-of-keys (a Hash Table keyed by position) trade speed for ease of building the matrix.
Matrix-vector product
Let be sparse and a vector of length . The product has entries
For a sparse matrix, the sum runs only over the stored entries in row , because all other terms are zero. The total work is one multiplication and one addition per nonzero, so the cost is proportional to . This is why the cost goes down as the matrix becomes sparser: in big-O terms it is rather than .
This is the same Matrix Multiplication idea, restricted to the nonzero entries: each row of takes a dot product with , and only the stored positions contribute.
Fill-in
Solving a linear system (finding the that the matrix maps to ) by Gaussian Elimination, which subtracts multiples of rows from other rows to clear entries, has a catch with sparse matrices. Elimination can turn zeros into nonzeros, an effect called fill-in. If fill-in is large, the matrix stops being sparse and memory explodes. Choosing a good order for the rows and columns before elimination keeps fill-in small. For this reason, sparse solvers spend effort on reordering before they compute anything.
Worked examples
Take the matrix
- Count the nonzeros: 5, 3, 1 and 2, so . The dense grid has 16 cells, so the density is .
- Scan row by row. Row 1 has the value 5 in column 1. Row 2 has 3 in column 3. Row 3 is empty. Row 4 has 1 in column 1 and 2 in column 4.
- So
valuesandcol_index. - For
row_ptr, row 1 starts at position 1, row 2 starts at position 2, row 3 starts at position 3 (it is empty, so the next row starts at the same place), and row 4 starts at position 3 as well. The end sentinel is the position after the last value, which is 5. Sorow_ptr. - Check row 4:
row_ptr[4]is 3 androw_ptr[5]is 5, so positions 3 and 4 are read. They give value 1 in column 1 and value 2 in column 4, which matches the matrix. - Interpretation: 4 numbers for the values, 4 for the columns and 5 for the pointers make 13 stored numbers, against 16 for the dense grid. At this tiny size the saving is small, but the pattern is the same at any size.
Many physics problems produce a matrix where each row has nonzeros only on the diagonal and its two neighbours. Take , so the matrix is .
- Dense storage: numbers.
- Nonzeros: each interior row has 3 entries, and the first and last have 2. The total is .
- CSR storage:
valueshas 2998 numbers,col_indexhas 2998 integers, androw_ptrhas 1001 integers. The total is stored numbers. - Compression ratio: . The sparse form is about 143 times smaller.
- Matrix-vector work: the dense product takes about multiplications and additions, while the sparse product takes about 3000. The sparse product is roughly 330 times cheaper in arithmetic.
- Interpretation: the saving comes entirely from the zeros the matrix does not store. Doubling doubles the sparse cost but quadruples the dense cost.
Suppose a web-link matrix has pages, and each page links to about 20 others on average. Each link is one nonzero, so the matrix has nonzeros.
- Dense storage: numbers. That is a trillion entries, far beyond the memory of a single ordinary machine.
- Sparse storage: about numbers, a little over 40 million.
- Compression ratio: about .
- One matrix-vector product costs about multiply-adds, against for the dense version. Repeated products, as in iterative ranking methods, are feasible only in the sparse form.
- Interpretation: the dense representation is not merely slow. It cannot be stored at all, so sparse storage is the difference between a computation that is possible and one that is not.
These numbers are illustrative, chosen to show the scale. They are not measurements of any real web graph.
Tradeoffs and failure modes
| Situation | Problem | Better choice |
|---|---|---|
| Matrix is mostly dense (density above a few tens of percent) | Sparse indexing adds overhead and can be slower than dense storage | Use a dense array |
| Matrix is built one entry at a time | Compressed formats are awkward to edit | Build in a coordinate or dictionary format, then convert |
| Elimination creates many new nonzeros (fill-in) | Memory and time grow quickly | Reorder rows and columns first, or use an iterative method (one that only multiplies by the matrix) |
| Access pattern needs columns quickly | CSR is fast for rows, slow for columns | Store a second copy in compressed sparse column (CSC) format |
| Nonzeros cluster in a band or block | A general format wastes space on the pattern | Use a banded or block format |
The most common mistake is to assume a matrix is sparse because it looks it. If the zeros are only a small fraction, the index arrays cost more than they save.
History
Sparse matrix methods grew out of the need to solve large systems of equations in structural engineering and circuit analysis, where the matrices come from local connections between parts. Practical elimination schemes that avoided storing zeros appeared in the mid twentieth century, and the growth of computer memory in the following decades turned them into standard tools. Iterative methods for sparse systems, which only ever multiply by the matrix, became central because they fit the sparse format so well. Modern numerical libraries provide several storage formats and reordering algorithms as a matter of course.
Recap
A sparse matrix stores its nonzero entries and their positions. Its products cost time proportional to the number of nonzeros, not to the number of cells, so most real large matrices are only usable in this form. The main risk is fill-in during elimination, which is why ordering matters. The next step is the adjacency matrix of a Graph, which is one of the most common sources of sparsity.
Check yourself
QuestionA matrix has 7 nonzero entries. How many cells are zero, and what is the density?Show answer
The grid has cells. Since 7 are nonzero, are zero. The density is , meaning 28 percent of the cells are filled.
QuestionIn CSR form, what does row_ptr[i+1] minus row_ptr[i] give?Show answer
It gives the number of stored nonzeros in row . The pointer marks where row starts in the values array, and the next pointer marks where row starts, so the difference is the count of that row's entries.
QuestionA matrix has 6000 nonzeros. Roughly how many multiply-adds does a sparse matrix-vector product need, compared with the dense product?Show answer
The sparse product needs about one multiply-add per nonzero, so about 6000. The dense product needs . The sparse product is roughly 670 times cheaper in arithmetic.
QuestionWhy might a matrix that is sparse at the start become expensive to solve with Gaussian elimination?Show answer
Elimination creates new nonzeros in positions that were zero before, a process called fill-in. If the matrix fills in heavily, the stored matrix stops being sparse and both the memory and the arithmetic grow sharply. Reordering rows and columns before elimination reduces the fill-in.