17 Numerical Linear Algebra in Depth
17.1 Learning objectives
By the end of this chapter you should be able to:
- Distinguish dense and sparse linear algebra and choose the appropriate representation for a given problem.
- Recognize the standard sparse storage formats (COO, CSR, CSC) and the
Matrixpackage’sdgCMatrix,dsCMatrix, anddgRMatrixclasses. - Choose between direct solvers (LU, Cholesky, QR) and iterative solvers (Conjugate Gradient, GMRES, BiCGSTAB) for a given linear system.
- Reuse a single matrix factorization across many right-hand sides instead of refactoring per solve.
- Reason about the BLAS layer: levels 1, 2, and 3 BLAS, what each level does, and which dominates the runtime of a given algorithm.
- Identify when alternative BLAS implementations (OpenBLAS, MKL, vecLib) materially change runtime.
- Use specialized storage (banded, symmetric, positive definite) and matching specialized solvers for matrices that have exploitable structure.
- Apply preconditioning for iterative solvers when the unpreconditioned condition number is too large for reasonable convergence.
17.2 Orientation
The linear algebra chapters of the first half, beginning with Chapter 5, covered dense matrix operations: %*%, solve, crossprod, the basic decompositions, and the OLS normal equations done correctly. That treatment assumed that the matrices fit in RAM and that all entries were potentially nonzero. Unfortunately, real biostatistical work routinely violates one or both assumptions. Design matrices for mixed-effects models with hundreds of subjects can be sparse, with most entries exactly zero. Genome-wide association matrices are large enough that direct factorization costs prohibitive memory. Matrices arising from PDE-based imaging methods have banded or block-banded structure, and the dense algorithms ignore it.
In this chapter we shall develop the tools for those cases. We begin with sparse storage and sparse algorithms. We then turn to iterative solvers, which never form the matrix factorization, and to the reuse of a factorization across many right-hand sides. Next we consider the BLAS layer that ultimately runs every dense algorithm beneath the R-language interface. Lastly, we treat specialized storage for structured matrices and work through a spatial smoothing example. Throughout, the emphasis is practical. That is, we ask which tool to reach for in which situation, and what the failure modes are when we reach for the wrong one.
17.3 The statistician’s contribution
The statistical question is the same whether we store \(X\) as a dense matrix or a sparse one. The cost, however, is not. The dense path may use 100 GB of RAM and run for a week, while the sparse path uses 100 MB and runs in an hour. Deciding which path a given problem permits is the analyst’s job; the software does not make that decision for us.
Recognize the structure before forming the matrix. A mixed-effects design matrix with subject-level random intercepts has a known sparsity pattern (one nonzero per row in the random-effects block), and we should exploit it. Forming a dense \((n \times q)\) block in which most entries are zero wastes orders of magnitude of memory and compute. The remedy lies upstream. That is, we build the matrix with Matrix::sparseMatrix from the start, rather than densifying a sparse construction.
Match solver to structure. A symmetric positive-definite system should use Cholesky rather than LU. A banded system should use a banded solver, and a least-squares system should use QR. The general-purpose solve(A, b) discards this exploitable structure. As a result it produces solutions an order of magnitude more slowly than necessary.
Direct vs. iterative is a regime decision. For \(n < 10^4\) and dense, direct solvers (LU, Cholesky, QR) are almost always the right choice. For \(n > 10^5\) and sparse, iterative solvers (CG, GMRES) become competitive or necessary. We note that the crossover depends on sparsity and conditioning as well as on size.
The BLAS choice matters more than the R code. A matrix multiplication that takes 30 seconds with the reference BLAS may take 3 seconds with OpenBLAS or 1 second with MKL. The R code is identical in all three cases. For matrix-heavy work, verifying the active BLAS via sessionInfo() is the single most useful diagnostic.
17.4 Sparse linear algebra
A matrix is sparse when most of its entries are zero and a specialized storage format can exploit the zeros. There is no fixed threshold. In practice, a matrix is worth treating as sparse when fewer than 10% of entries are nonzero and the matrix is large enough that ordinary dense storage is wasteful.
17.4.1 Sparse storage formats
Three formats appear repeatedly, and each represents only the nonzero entries.
COO (coordinate list). This format is a list of triples (i, j, x) giving the row, column, and value of each nonzero. It is the simplest of the three and is convenient for construction from a data frame. It is not, however, efficient for matrix operations.
CSR (compressed sparse row). This format uses three arrays: the nonzero values in row-major order, the column indices of those values, and a row-pointer array indicating where each row starts. It is efficient for row-wise operations and for sparse matrix-vector products \(A \mathbf{x}\).
CSC (compressed sparse column). This format is the transpose of CSR. That is, it stores the nonzero values in column-major order, their row indices, and a column-pointer array. It is efficient for column-wise operations and for sparse matrix-vector products \(A^T \mathbf{x}\). It is also the default in R’s Matrix package.
library(Matrix)
# 5x5 sparse matrix; only 6 nonzero entries
A <- sparseMatrix(
i = c(1, 2, 3, 3, 4, 5),
j = c(1, 2, 1, 3, 4, 5),
x = c(2.0, 1.5, 0.5, 3.0, 1.0, 2.5),
dims = c(5, 5)
)
class(A)
#> [1] "dgCMatrix" # general sparse, column-compressed
object.size(A)
#> 1248 bytes # vs ~200 bytes for dense 5x5,
# but for 1000x1000 with 6000 nonzeros
# sparse is ~30 KB vs dense 8 MB
# operations work like dense, but exploit sparsity
b <- runif(5)
solve(A, b) # uses sparse LUThe Matrix package organizes its classes as follows.
| Class | Properties |
|---|---|
dgCMatrix |
General sparse, double, column-compressed |
dsCMatrix |
Symmetric sparse, double, column-compressed |
dtCMatrix |
Triangular sparse, double, column-compressed |
dgRMatrix |
General sparse, double, row-compressed |
lgCMatrix |
General sparse, logical, column-compressed |
nsCMatrix |
Pattern (nonzero structure only), symmetric |
The reader will note that the class names follow a simple code. The d prefix denotes double precision, l logical, and n pattern. The next letter gives the structural property: g general, s symmetric, t triangular. The last letter gives the storage: C column, R row, T triplet. For most user code, dgCMatrix is the default.
17.4.2 Sparse matrix-vector and matrix-matrix products
The sparse matrix-vector product (\(A \mathbf{x}\)) is the workhorse operation in iterative solvers. Its cost is proportional to the number of nonzero entries rather than to \(n^2\). In symbols, for a sparse matrix with \(k\) nonzeros, \(A\mathbf{x}\) is \(O(k)\) rather than \(O(n^2)\).
Sparse matrix-matrix products (\(A B\)) generally produce denser output than either input. A sparse-times-sparse product that fills in many entries (high fill-in) loses the sparsity advantage. In such cases the operation may be slower than its dense equivalent. It is therefore advisable to compute the sparsity of the result before assuming that sparse multiplication is faster.
17.4.3 When to use sparse storage
- Yes, sparse: mixed-effects design matrices with subject-specific random effects, regression with many one-hot-encoded factor levels, kernel matrices with thresholded entries, finite-difference operators on grids, graph adjacency matrices, GWAS genotype matrices stored as 0/1/2.
- Probably not sparse: small dense matrices (under \(1000 \times 1000\)), correlation matrices for which every pair has nonzero correlation, design matrices with continuous covariates and no factor-encoded predictors.
- Maybe sparse: large design matrices where the sparsity is moderate (10 to 40%); benchmark to decide.
17.5 Iterative solvers
Direct methods (LU, Cholesky, QR) compute the factorization explicitly and use it to solve the system. On the plus side, they are exact up to floating-point error and predictable in runtime. On the minus side, they are \(O(n^3)\) in time and \(O(n^2)\) in memory for dense matrices. For large sparse problems the factorization often produces fill-in that destroys the sparsity. In that case the direct method becomes impractical.
Iterative solvers, by contrast, never form a factorization. They compute an approximation to the solution by repeatedly applying the matrix to a sequence of vectors. Each iteration involves one or two matrix-vector products and a few inner products. We note that convergence is governed by the matrix’s spectrum rather than by its dimension.
17.5.1 Conjugate gradient (CG)
For symmetric positive-definite systems, the conjugate gradient method finds the exact solution in at most \(n\) iterations. When the eigenvalues are clustered, it finds an approximate solution in far fewer. Each iteration costs one matrix-vector product plus \(O(n)\) work.
# pseudocode
cg <- function(A, b, x0 = rep(0, length(b)),
tol = 1e-8, max_iter = length(b)) {
x <- x0
r <- b - A %*% x
p <- r
for (k in seq_len(max_iter)) {
Ap <- A %*% p
alpha <- as.numeric(crossprod(r) / crossprod(p, Ap))
x <- x + alpha * p
r_new <- r - alpha * Ap
if (sqrt(sum(r_new^2)) < tol) break
beta <- as.numeric(crossprod(r_new) / crossprod(r))
p <- r_new + beta * p
r <- r_new
}
x
}CG is the standard tool for SPD systems whose factorization would be too expensive. Common applications include covariance-matrix solves in Bayesian models, the normal equations in penalized regression, and kernel-method linear systems.
17.5.2 GMRES
For general (non-symmetric) systems, the Generalized Minimal Residual method (GMRES) is the analog of CG. Unfortunately, it is more expensive per iteration, since its memory grows linearly in the iteration count. For this reason it is typically restarted every \(m\) iterations to bound the memory.
In R, the Rlinsolve package provides CG, GMRES, BiCGSTAB, and others.
17.5.3 BiCGSTAB and other variants
Biconjugate Gradient Stabilized (BiCGSTAB) is a popular choice for non-symmetric systems in which the memory growth of GMRES is a problem. Its convergence is less predictable, but its per-iteration cost is fixed.
17.5.4 Preconditioning
The convergence rate of an iterative method depends on the condition number of the matrix. For poorly-conditioned systems, we apply a preconditioner \(M\) so that \(M^{-1} A \mathbf{x} = M^{-1} \mathbf{b}\) has a better-conditioned coefficient matrix. The preconditioner \(M\) should approximate \(A\) but be much cheaper to invert.
Three preconditioners are in common use.
- Diagonal (Jacobi). \(M = \text{diag}(A)\). Cheap; mild improvement.
- Incomplete Cholesky / LU. Compute a factorization but allow only certain fill-in patterns. Trade preconditioning quality for cost.
- Algebraic multigrid (AMG). For matrices arising from PDEs on grids; complex but very effective.
For most biostatistical applications, diagonal preconditioning is sufficient, if it is needed at all. The more complex preconditioners belong to specialist domain expertise.
17.5.5 Direct vs. iterative regime decision
| Setting | Direct (LU/Cholesky/QR) | Iterative (CG/GMRES) |
|---|---|---|
| Dense, \(n < 10^4\) | Yes | No |
| Dense, \(n > 10^5\) | Memory-prohibitive | Yes |
| Sparse, low fill-in | Yes (sparse direct) | Optional |
| Sparse, high fill-in | No | Yes |
| Many right-hand sides, same matrix | Yes (factor once) | Less efficient |
| One right-hand side, large matrix | Less efficient | Yes |
| Need solution to high precision | Yes | Slower |
| Need approximate solution | Same cost | Stop early; faster |
17.6 Reusing factorizations
A common antipattern is to solve \(A \mathbf{x}_i = \mathbf{b}_i\) for many right-hand sides \(\mathbf{b}_i\) by calling solve(A, b_i) in a loop. The difficulty is that each call refactorizes \(A\).
# bad: O(n^3) per call
results <- vector("list", 100)
for (i in seq_len(100)) {
results[[i]] <- solve(A, B[, i])
}
# good: factorize once, solve many times
A_factor <- chol(A) # for SPD; use lu() / qr() otherwise
results <- matrix(0, nrow(A), 100)
for (i in seq_len(100)) {
results[, i] <- backsolve(A_factor, forwardsolve(t(A_factor), B[, i]))
}In the second version the factorization cost is paid once. Each subsequent solve is then \(O(n^2)\) (back-substitution) rather than \(O(n^3)\). For 100 right-hand sides on a \(1000 \times 1000\) matrix, the saving is two orders of magnitude.
The same pattern applies to QR for least squares with many response vectors.
qrA <- qr(A)
betas <- qr.coef(qrA, Y) # solves for all columns of Y at once17.7 The BLAS layer
Beneath the R interface, R’s matrix operations dispatch to BLAS (Basic Linear Algebra Subprograms). BLAS is organized in three levels.
- Level 1 BLAS. Vector-vector operations: dot product, scalar-vector multiply (
axpy). Cost \(O(n)\). - Level 2 BLAS. Matrix-vector operations: matrix-vector multiply (
gemv). Cost \(O(n^2)\). - Level 3 BLAS. Matrix-matrix operations: matrix-matrix multiply (
gemm). Cost \(O(n^3)\).
It is at level 3 that high-performance implementations make the largest difference. A naive triple loop for \(C = AB\) is \(O(n^3)\), but it runs at perhaps 5 to 10% of theoretical peak performance because of poor cache utilization. Optimized BLAS implementations (OpenBLAS, MKL, vecLib on macOS) use cache blocking, SIMD instructions, and threading. In this way they reach 60 to 90% of peak performance.
We may check which BLAS R is using as follows.
sessionInfo()
#> ...
#> Matrix products: default
#> BLAS: /usr/lib/x86_64-linux-gnu/openblas-pthread/libblas.so.3
#> LAPACK: /usr/lib/x86_64-linux-gnu/openblas-pthread/liblapack.so.3Unfortunately, the reference BLAS that ships with stock R on Linux is slow. OpenBLAS and MKL produce 5 to 20× speedups on matrix-heavy code with no R-level changes. On macOS, R typically uses Apple’s vecLib (Accelerate framework), which is already optimized.
On Linux, we may switch BLAS implementations as follows.
sudo apt install libopenblas-dev
sudo update-alternatives --config libblas.so.3-x86_64-linux-gnuThe change is transparent to R code, and benchmarks improve immediately.
For matrix-heavy production work, verifying the BLAS is the single most effective performance check. A poor BLAS choice costs a 5 to 20× slowdown on every numerical operation. That cost persists across the life of the code, and nothing in the output signals it.
17.8 Specialized storage and solvers
Some matrices have exploitable structure beyond sparsity. For these, specialized storage and matched solvers offer further gains.
17.8.1 Banded matrices
A matrix is banded if all nonzero entries lie within a narrow diagonal band. Banded matrices arise in time-series analysis (autoregressive structure), spline smoothing (B-spline basis), and finite-difference methods. Banded LU factorization is \(O(n b^2)\), where \(b\) is the bandwidth. This is much faster than the general \(O(n^3)\).
library(Matrix)
# 1000x1000 tridiagonal matrix
n <- 1000
A <- bandSparse(n, n,
k = -1:1,
diagonals = list(rep(-1, n - 1),
rep(2, n),
rep(-1, n - 1)))
class(A) # "dsCMatrix" (sparse symmetric)
solve(A, runif(n)) # uses banded solver17.8.2 Symmetric positive-definite matrices
Recall that the Cholesky decomposition \(A = L L^T\) exists for SPD matrices. The factorization is roughly half the cost of a general LU, and the back-substitution is similar.
A_chol <- chol(A) # upper triangular R such that A = R'R
x <- backsolve(A_chol, # solve R x = ...
forwardsolve(t(A_chol), # solve R' z = b
b))For sparse SPD matrices the same idea applies via Matrix::Cholesky(). This function uses a fill-reducing permutation (typically AMD or METIS) to reduce fill-in during factorization.
17.8.3 Symmetric indefinite
Symmetric matrices that are not positive definite (e.g., KKT systems in constrained optimization) use the LDLT decomposition. In symbols, \(A = L D L^T\), where \(D\) is block-diagonal. LAPACK’s dsytrf provides this decomposition.
17.8.4 Toeplitz and circulant
Toeplitz matrices have constant diagonals. That is, every \(T_{i,j}\) depends only on \(i - j\). They arise in time-series analysis and signal processing. Circulant matrices are diagonalized by the discrete Fourier transform, so matrix-vector multiplication is \(O(n \log n)\) via FFT.
For most biostatistical work, banded and sparse-SPD matrices are the two structural specializations that matter most. We now illustrate both in a single example.
17.9 Worked example: GMRF for spatial smoothing
To illustrate, consider a Gaussian Markov random field (GMRF) prior on a regular grid. Such a prior produces a sparse precision matrix \(Q\) with banded structure. Given observations \(y\) and the GMRF prior, the posterior mean is the solution to
\[ (Q + \tau I) \boldsymbol\mu = \tau \mathbf{y} \]
where \(\tau\) is the observation precision. For a \(100 \times 100\) grid, \(Q\) is \(10{,}000 \times 10{,}000\). It is sparse, with about 50{,}000 nonzeros, since each cell has 4 neighbors plus itself.
library(Matrix)
# build a 1D GMRF precision (just for illustration; 2D is similar)
n <- 1000
Q <- bandSparse(n, n,
k = -1:1,
diagonals = list(rep(-1, n - 1),
rep(2, n),
rep(-1, n - 1)))
Q[1, 1] <- 1 # boundary
Q[n, n] <- 1
tau <- 0.1
y <- rnorm(n)
# dense path: too expensive for n = 10000+
# system <- as.matrix(Q + tau * Diagonal(n))
# solve(system, tau * y) # would refactorize general LU
# sparse Cholesky path
M <- Q + tau * Diagonal(n)
M_chol <- Cholesky(M, perm = TRUE, super = FALSE)
mu <- solve(M_chol, tau * y)
# can also solve for many y at once
Y <- matrix(rnorm(n * 100), n, 100)
mu_mat <- solve(M_chol, tau * Y) # one factorization, 100 solvesThe Cholesky factor is reused across all 100 right-hand sides. The cost is therefore one factorization plus 100 cheap back-substitutions, instead of 100 separate factorizations.
17.10 Collaborating with an LLM on numerical linear algebra
LLMs handle the syntactic translation between dense and sparse storage well. They are weaker at the structural recognition step, that is, deciding whether to use sparse storage at all and choosing the right solver. They are also weaker at BLAS-related diagnostics.
Prompt 1: choosing the right representation. Describe the matrix (dimensions, structural properties, sparsity pattern, frequency of operations) and ask: ‘should I use dense or sparse storage? If sparse, which Matrix class? Justify the choice in terms of memory and operation cost.’
What to watch for. The LLM should consider three questions. First, do operations against this matrix produce dense intermediate results, which would defeat the sparse representation? Second, are structural properties such as symmetry or positive-definiteness exploitable? Third, what is the ratio of construction cost to solve cost? If the LLM offers a generic ‘use sparse if more than 80% zeros’ rule, we should press for the structural specifics of the problem.
Verification. Build the matrix both ways on a small test case and benchmark a representative operation. If the choice is correct, the sparse path should be faster and use less memory.
Prompt 2: factorization reuse. Paste a function that calls solve(A, b) repeatedly with the same \(A\) and ask: ‘rewrite to factorize once and reuse the factorization across the loop, and explain the asymptotic improvement.’
What to watch for. The rewrite should call one of chol, lu, qr, or Cholesky (for sparse) at the top of the loop, and backsolve/forwardsolve or qr.coef/solve(factor, b) inside it. The asymptotic improvement depends on the structure of \(A\). If \(A\) is general, the gain is \(O(n^3) \to O(n^2)\) per solve. If \(A\) is SPD, Cholesky offers a half-cost factorization. If \(A\) is sparse with low fill-in, the improvement is potentially much larger.
Verification. Benchmark both versions on a moderately large \(A\) and many right-hand sides. The factorization-reuse version should be substantially faster.
Prompt 3: BLAS diagnosis. Paste the output of sessionInfo() plus a benchmark showing slow matrix multiplication and ask: ‘is the BLAS the bottleneck? Recommend a faster alternative for this platform.’
What to watch for. The reference BLAS is slow. It shows up as no link mentioned in the BLAS line, or as libblas.so without OpenBLAS or MKL. On Linux the LLM should recommend OpenBLAS or MKL, and on macOS it should identify Apple’s vecLib as already fast. If the BLAS is already optimized, the bottleneck lies elsewhere, and the LLM should turn to other diagnostics.
Verification. Switch the BLAS, restart R, and re-run the benchmark. A 5 to 20× improvement on dense matrix multiply confirms that the BLAS was the bottleneck. If the improvement is small, the bottleneck was something else.
We note that a numerical linear algebra problem can sit in any of three layers, and each is diagnosed separately. The first is the R-level code. The second is the BLAS, which determines performance. The third is the matrix structure, which determines which algorithm is appropriate.
17.11 Principle in use
Three habits define defensible numerical linear algebra:
- Recognize structure first. Sparse, banded, symmetric, positive-definite. The structural recognition determines algorithm, storage, and conditioning behavior.
- Factorize once, solve many times. Reuse factorizations across right-hand sides. The pattern converts \(O(kn^3)\) into \(O(n^3 + kn^2)\), a large gain for \(k\) even moderately large.
- Verify the BLAS. A fast BLAS is the single most effective performance change.
sessionInfo()tells you what is installed; benchmarks tell you whether it is fast.
17.12 Exercises
- Build a sparse \(1000 \times 1000\) tridiagonal matrix with
Matrix::bandSparse. Compute its memory usage versus the dense equivalent. Solve a linear system against it; benchmark against the densesolve. - Implement conjugate gradient from the pseudocode in this chapter. Apply to a \(5000 \times 5000\) sparse SPD matrix. Compare convergence iterations against the dimension; convergence should be much faster than \(n\) if the eigenvalues are clustered.
- For a regression with 100 different response vectors \(\mathbf{y}_1, \ldots, \mathbf{y}_{100}\) and a common design matrix \(X\), write the loop two ways: one calling
lm()100 times, one factorizing \(X\) once and reusing. Time both. Report the speedup. - Check your R installation’s BLAS via
sessionInfo(). Runbench::mark(A %*% B)on \(A, B\) each \(1000 \times 1000\). If your BLAS is the reference BLAS, install OpenBLAS or MKL and re-run. Document the speedup. - The Hilbert matrix has condition number \(\sim 10^{18}\) for \(n = 12\). Solve \(H \mathbf{x} = \mathbf{b}\) with exact \(\mathbf{x} = \mathbf{1}\) via a direct solver and via CG with diagonal preconditioning. Compare the forward errors.
17.13 Further reading
- (Golub & Van Loan, 2013) Chapters 4 to 7, the canonical reference for direct methods, including sparse direct.
- (Saad, 2003), Iterative Methods for Sparse Linear Systems. Free PDF at
www-users.cse.umn.edu/~saad. - (Bates & Maechler, 2010), the
Matrixpackage vignettes, in particular ‘Sparse Matrix Classes’ and ‘Sparse Cholesky’. - The
Rlinsolvepackage documentation for accessible R implementations of CG, GMRES, BiCGSTAB.