TExcelTAD
Home › MATLAB / Octave › Sparse Matrices

Sparse Matrices

Many large matrices are almost entirely zeros. A finite-difference grid with a million points gives a million-by-million matrix, but each row has only five non-zero entries; road networks, social graphs, circuit equations and finite-element models look the same. Storing all those zeros would need terabytes of memory, and multiplying by them wastes time. A sparse matrix stores only the non-zero entries and their positions, and MATLAB's operators, backslash included, work on it directly.

Creating sparse matrices

Function Creates
sparse(A) A sparse copy of a full matrix
sparse(i, j, v, m, n) An m×n matrix with S(i(k), j(k)) = v(k); duplicates are added
sparse(m, n) An all-zero m×n sparse matrix
speye(n) The sparse identity
spdiags(B, d, m, n) Columns of B placed on the diagonals listed in d
sprand, sprandn, sprandsym Random sparse matrices for testing
full(S) Back to an ordinary (full) matrix

The triplet form sparse(i, j, v) is the usual way to build one: collect row indices, column indices and values in three vectors, then create the matrix in a single call. Repeated (i, j) pairs are summed, which is exactly what assembling a finite-element or network matrix needs:

matlab · try it yourself
i = [1 2 3 3 1];
j = [1 2 1 3 1];                  % (1,1) appears twice
v = [4 5 6 7 10];
S = sparse(i, j, v, 3, 3);
disp(full(S))
fprintf('nnz = %d, density = %.0f%%, issparse = %d\n', nnz(S), 100 * nnz(S) / numel(S), issparse(S));
[r, c, val] = find(S);
fprintf('(%d,%d) = %g\n', [r c val]');
   14    0    0
    0    5    0
    6    0    7
nnz = 4, density = 44%, issparse = 1
(1,1) = 14
(3,1) = 6
(2,2) = 5
(3,3) = 7

nnz counts the stored non-zeros, find returns them as triplets (in column order, which is how they are stored), and nonzeros(S) gives just the values.

Displaying a sparse matrix without a semicolon lists its non-zero entries, but the layout differs between the two programs. Octave prints a header and -> arrows:

matlab · try it yourself
S = sparse([1 2 3], [1 2 1], [4 5 6], 3, 3)
S =

Compressed Column Sparse (rows = 3, cols = 3, nnz = 3 [33%])

  (1, 1) -> 4
  (3, 1) -> 6
  (2, 2) -> 5

MATLAB output:

matlab
S =

  3×3 sparse double matrix (3 nonzeros)

   (1,1)        4
   (3,1)        6
   (2,2)        5

For small examples, full(S) or disp(full(S)) shows the familiar grid in both.

Banded matrices and memory

spdiags builds band matrices. The classic one is the second-difference matrix with 2 on the diagonal and −1 beside it, which approximates −d²/dx². Here is a 10 000 × 10 000 version; as a full matrix it would need 800 MB, so we never create it with full:

matlab · try it yourself
n = 10000;
e = ones(n, 1);
T = spdiags([-e 2*e -e], -1:1, n, n);
fprintf('size %dx%d, nnz = %d (%.3f%% of the entries)\n', size(T), nnz(T), 100 * nnz(T) / n^2);
fullBytes   = 8 * n^2;                    % 8 bytes per double
sparseBytes = 16 * nnz(T) + 8 * (n + 1);  % value + row index per entry, plus column pointers
fprintf('full storage:   %8.1f MB\n', fullBytes / 1e6);
fprintf('sparse storage: %8.3f MB\n', sparseBytes / 1e6);
fprintf('ratio: about %.0f times smaller\n', fullBytes / sparseBytes);
size 10000x10000, nnz = 29998 (0.030% of the entries)
full storage:      800.0 MB
sparse storage:    0.560 MB
ratio: about 1429 times smaller

Both MATLAB and Octave store sparse matrices in compressed sparse column (CSC) form: for every non-zero, its value (8 bytes) and row index (8 bytes), plus one pointer per column. whos T reports the real number of bytes. The rule of thumb: sparse storage pays off once fewer than about a third to a half of the entries are non-zero, and for the huge matrices where it matters, density is usually far below 1%.

Which operations stay sparse?

Operations that cannot create new non-zeros keep the result sparse; operations that fill in everything make it full:

matlab · try it yourself
S = speye(4) * 3;
F = ones(4);
fprintf('S + S     sparse: %d\n', issparse(S + S));
fprintf('S .* F    sparse: %d\n', issparse(S .* F));
fprintf('S * 2     sparse: %d\n', issparse(S * 2));
fprintf('S'' (transpose) sparse: %d\n', issparse(S'));
fprintf('S + 1     sparse: %d\n', issparse(S + 1));
fprintf('S * F     sparse: %d\n', issparse(S * F));
fprintf('nnz(S) = %d, nnz(exp(S)) = %d\n', nnz(S), nnz(exp(S)));
S + S     sparse: 1
S .* F    sparse: 1
S * 2     sparse: 1
S' (transpose) sparse: 1
S + 1     sparse: 0
S * F     sparse: 0
nnz(S) = 4, nnz(exp(S)) = 16

Watch out for S + 1 and for functions like exp or cos that map 0 to a non-zero value: exp(S) has 16 non-zeros out of 16, and on a large matrix such a result is effectively full, however it is stored. Functions that keep 0 at 0 (abs, sqrt, sin, round) preserve the sparsity pattern. Also avoid growing a sparse matrix element by element inside a loop (S(i, j) = v re-packs the storage every time); collect triplets and call sparse once.

Solving sparse systems

Backslash detects sparse input and switches to sparse direct solvers (banded, Cholesky or LU with reordering to limit fill-in). As an application, solve the boundary-value problem −u″ = π² sin(πx) on [0, 1] with u(0) = u(1) = 0. The exact solution is u = sin(πx), so we can measure the error of the finite-difference approximation:

matlab · try it yourself
n = 999;                           % interior grid points
h = 1 / (n + 1);
x = (1:n)' * h;
e = ones(n, 1);
A = spdiags([-e 2*e -e], -1:1, n, n) / h^2;
f = pi^2 * sin(pi * x);
u = A \ f;
fprintf('nnz(A) = %d, max error = %.2e\n', nnz(A), max(abs(u - sin(pi * x))));
fprintf('u(0.5) = %.6f (exact 1)\n', u(x == 0.5));
nnz(A) = 2995, max error = 8.22e-07
u(0.5) = 1.000001 (exact 1)

The error of about 10⁻⁷ comes from the discretisation (it shrinks with h²), not from the solver. The same solve with a full 999×999 matrix gives the same answer but stores a million numbers instead of three thousand.

Two dimensions with kron

The 2-D Laplacian on an m×m grid is built from the 1-D one with Kronecker products. spy(A) plots the sparsity pattern, one dot per non-zero:

matlab
m = 5;
e = ones(m, 1);
T = spdiags([-e 2*e -e], -1:1, m, m);
A = kron(speye(m), T) + kron(T, speye(m));
spy(A)
title('2-D Laplacian, 5 x 5 grid')

Each row has at most five non-zeros: the point itself and its four neighbours. Solving a heat-distribution problem on a 100×100 grid means a 10 000-unknown system, which sparse backslash handles in a fraction of a second:

matlab · try it yourself
m = 100;
h = 1 / (m + 1);
e = ones(m, 1);
T = spdiags([-e 2*e -e], -1:1, m, m);
A = (kron(speye(m), T) + kron(T, speye(m))) / h^2;
f = ones(m^2, 1);                  % uniform heat source, edges held at 0
u = A \ f;
U = reshape(u, m, m);
fprintf('unknowns: %d, nnz: %d, density: %.4f%%\n', m^2, nnz(A), 100 * nnz(A) / numel(A));
fprintf('hottest point: %.6f at the centre: %d\n', max(u), max(u) == max(max(U(50:51, 50:51))));
unknowns: 10000, nnz: 49600, density: 0.0496%
hottest point: 0.073653 at the centre: 1

Iterative solvers and eigs

For really large systems even sparse factorisation runs out of memory, and iterative methods take over. They only need matrix-vector products. pcg (preconditioned conjugate gradients) is for symmetric positive definite matrices; gmres and bicgstab handle general ones. eigs computes a few eigenvalues of a large sparse matrix without touching the rest:

matlab · try it yourself
n = 200;
e = ones(n, 1);
T = spdiags([-e 2*e -e], -1:1, n, n);
b = T * ones(n, 1);                % right-hand side with known solution
[x, flag] = pcg(T, b, 1e-10, 500);
fprintf('pcg converged: %d, max error below 1e-6: %d\n', flag == 0, max(abs(x - 1)) < 1e-6);
lam = sort(eigs(T, 3, 'sm'));      % three eigenvalues closest to 0
k = (1:3)';
exact = 4 * sin(k * pi / (2 * (n + 1))).^2;
fprintf('eigs: %.8f, exact: %.8f\n', [lam exact]');
pcg converged: 1, max error below 1e-6: 1
eigs: 0.00024429, exact: 0.00024429
eigs: 0.00097708, exact: 0.00097708
eigs: 0.00219822, exact: 0.00219822

The iteration count of pcg and the order in which eigs returns its values can differ between versions, which is why the example checks the flag and sorts the eigenvalues. Newer MATLAB prefers the name 'smallestabs' for the 'sm' option; Octave 11 only accepts 'sm' (which MATLAB still understands).

Summary

Task Function
Build from triplets sparse(i, j, v, m, n)
Band / identity spdiags, speye
Inspect nnz, nonzeros, find, issparse, spy
Convert sparse(A), full(S)
Solve A \ b (direct), pcg, gmres, bicgstab (iterative)
A few eigenvalues eigs(A, k, 'sm'), svds

Learn more: factorisations of full matrices are covered in Matrix Decompositions; the Python equivalents are in SciPy sparse data and sparse linear algebra.

Test yourself

What happens to repeated (i, j) pairs in sparse(i, j, v)?

  1. The last value wins
  2. Their values are added together
  3. An error is raised
  4. Only the first one is kept

S is a large sparse matrix. Which result is NOT sparse?

  1. S * 2
  2. S .* ones(size(S))
  3. S + 1
  4. S'

Why should you avoid filling a sparse matrix with S(i, j) = v in a loop?

  1. It is not allowed
  2. Each insertion re-packs the compressed storage, which is very slow
  3. It converts S to full
  4. It ignores zero values