Pedagogical examples
Here are two pedagogical examples per phase, from Phase 1 through Phase 7, as a gentle and progressive
introduction to MTL5. Each example is grounded in a historical numerical problem that showcases the
MTL5 functionality introduced in that phase. The programs are in examples/, one directory per phase.
Where an example has an animation, it replays the numbers the example program computes: the program
writes them with --trace <file>, and the page draws them. Each animation has play, step and scrub
controls, and with reduced motion it rests on its final frame.
Phase 1: Containers (dense2D, dense_vector, compressed2D, the Inserter)
Section titled “Phase 1: Containers (dense2D, dense_vector, compressed2D, the Inserter)”Example 1A: Leontief’s Input-Output Economy
Section titled “Example 1A: Leontief’s Input-Output Economy”Numerical goal: Find the gross output x that each sector of an economy must produce so that, after supplying what the other sectors consume, the final demand d is left over: x = d + Ax, or (I − A)x = d. The example solves it the way Leontief explained it, as rounds of production, x = d + Ad + A²d + …
Wassily Leontief built input-output tables of the American economy for 1919 and 1929 (“The Structure of American Economy”, 1941), and they won him the 1973 Nobel prize in economics. The rounds of production are the first iterative method most readers meet: each round needs only a matrix-vector product, and it converges because every column of A sums to less than one.
MTL5 features demonstrated:
- dense2D and dense_vector from initializer lists
- element access A(i, j), num_rows(), num_cols(), size()
- value semantics: a copy is a deep copy
- the same matrix in row-major and column-major storage
- A * v and += as the only operations the rounds need
Program: examples/phase01_core_types/leontief_economy.cpp
Loading the trace…
Each bar is a sector's gross output. Round 0 delivers the final demand d; round k adds Aᵏd, the inputs that the previous round used up. The dashed outline is the converged output. The small plot is the residual ‖d − (I − A)x‖ / ‖d‖ after each round.
The residual shrinks by a factor of about 0.48 per round, and 30 rounds reach 1e-10. Every column of A sums to at most 0.67. Total output is 774.3 for a final demand of 420, so the economy-wide multiplier is 1.84. Mining has the largest multiplier, 5.89: consumers buy little of it, but the other sectors use a lot.
Example 1B: Kirchhoff’s Laws and the Wheatstone Bridge
Section titled “Example 1B: Kirchhoff’s Laws and the Wheatstone Bridge”Numerical goal: Assemble the conductance matrix L of a resistor network, so that Kirchhoff’s current law reads L v = i for the node voltages v. Each resistor adds a 2 × 2 “stamp” to L, and the matrix is the sum of its stamps.
Gustav Kirchhoff stated his circuit laws in 1845. The network is the Wheatstone bridge, which Samuel Christie invented in 1833 and Charles Wheatstone made famous in 1843 for measuring an unknown resistance. Summing stamps is how every circuit simulator and finite element code assembles its matrix, and the bridge is small enough to show every entry.
MTL5 features demonstrated:
- compressed2D assembled with an inserter and update_plus, so repeated stamps add up
- a second inserter amending the finished matrix
- the CSR arrays behind it: ref_major(), ref_minor(), ref_data()
- sparse against dense storage as the network grows to a 64 × 64 mesh
Program: examples/phase01_core_types/kirchhoff_network.cpp
Loading the trace…
Each resistor of conductance g between nodes a and b adds g to L(a,a) and L(b,b) and subtracts g
from L(a,b) and L(b,a). The inserter uses update_plus, so stamps that land on the same
entry add up: L(1,1) collects R1, R2 and R5. After the five stamps the matrix has 14 stored
entries. (0,3) and (3,0) are never stored, because no resistor joins nodes 0 and 3. Compressed row
storage keeps three arrays: where each row starts, the column of each entry, and its value.
With R1/R2 = R3/R4 the bridge is balanced: both middle nodes sit at 6.6667 V and no current flows through the galvanometer R5. A second inserter then amends the finished matrix: one more stamp of the conductance difference changes R4 to 250 Ω, and 1.98 mA flows through R5. On a 64 × 64 mesh the same storage holds 20224 entries in 348 KiB, where a dense matrix would need 128 MiB.
Phase 2: Views and Permutations (trans, mapped, permutation_matrix, reorder)
Section titled “Phase 2: Views and Permutations (trans, mapped, permutation_matrix, reorder)”Example 2A: Dürer’s Magic Square, Through Views
Section titled “Example 2A: Dürer’s Magic Square, Through Views”Numerical goal: Verify the claims of the magic square in Dürer’s engraving Melencolia I (1514): every row, column and diagonal sums to 34, and so do the quadrants, the centre block and the four corners. Then find which rearrangements of the square keep it magic.
A 4 × 4 square is small enough to see every cell, and checking its sums needs exactly the operations views provide: a column is a row of the transpose, a quadrant or the four corners are sub-matrices, and the anti-diagonal is the diagonal of the row-reversed square. None of them copies an element.
MTL5 features demonstrated:
- trans(M) as a transposed view
- mapped(M, rows, cols) for contiguous and scattered sub-matrices
- permutation_matrix: P * M reorders rows; reorder(M, p) is P M Pᵀ
- views are live: they read the matrix as it is now
- one generic is_magic() that takes the matrix and every view of it
Program: examples/phase02_views_permutations/durer_magic_square.cpp
Loading the trace…
The first 16 frames each highlight the cells that one view reads, with the
MTL5 expression that selects them and their sum. Rows are rows of mapped(M, {i}, all),
columns are rows of trans(M), and the anti-diagonal is the diagonal of the row-reversed
J M. The quadrants, the centre block and the four corners are 2 × 2 mapped views.
All 16 sum to 34.
The last 7 frames move each number to its place under a rearrangement. 6 of them keep the square magic: the symmetries of the square, and the symmetric swap of row and column pairs. "swap rows 0 and 1" (P * M, P = {1, 0, 2, 3}) keeps every row and column sum but breaks both diagonals, which are then drawn in red.
Example 2B: Cuthill-McKee: Renumbering a Mesh
Section titled “Example 2B: Cuthill-McKee: Renumbering a Mesh”Numerical goal: Take the matrix of a 12 × 12 grid whose nodes were numbered in a scrambled order, and find a numbering that brings its nonzeros back next to the diagonal. Measure the bandwidth and the profile before and after.
Elizabeth Cuthill and James McKee (1969) proposed numbering the nodes breadth-first from a corner, so that neighbours get nearby numbers. Alan George (1971) found that reversing the order (Reverse Cuthill-McKee) also reduces fill in a later factorization. Renumbering is a permutation, applied to rows and columns together.
MTL5 features demonstrated:
- permutation vectors p[new] = old: invert_permutation, compose_permutations, is_valid_permutation
- sparse::util::symmetric_permute for B = P A Pᵀ
- mapped(A, p, p) as the same matrix without building it
- sparse::ordering::rcm on the scrambled matrix
Program: examples/phase02_views_permutations/bandwidth_reduction.cpp
Loading the trace…
Left: the 144 × 144 matrix of a 12 × 12 grid, one dot per nonzero. Right: the grid, each node shaded by its number, from faint (0) to full colour (143). The frames are the same matrix under three numberings: row by row, a shuffle such as a mesh generator might produce, and reverse Cuthill-McKee computed from the shuffled matrix alone.
Bandwidth max |i − j|: 12 row by row, 128 shuffled,
12 after RCM. The profile, the entries a skyline solver stores, is
1595, 6519 and 1210. RCM's numbering spreads from a
corner of the grid in diagonal wavefronts, the breadth-first levels of the matrix's graph.
symmetric_permute(A, p) and the view mapped(A, p, p) agree on every entry:
yes.
Phase 3: Basic Iterative Solvers (CG, BiCGSTAB, Iteration Control, Preconditioners)
Section titled “Phase 3: Basic Iterative Solvers (CG, BiCGSTAB, Iteration Control, Preconditioners)”Example 3A: Heat Equation on a 1D Rod (Steady-State)
Section titled “Example 3A: Heat Equation on a 1D Rod (Steady-State)”Numerical goal: Solve the 1D Poisson equation -u”(x) = f(x) on [0,1] with Dirichlet boundary conditions using finite differences. This produces a symmetric positive-definite (SPD) tridiagonal system Au = b.
This is the “hello world” of PDE numerical methods — every numerical analysis textbook (Trefethen & Bau, LeVeque) starts here. Students see how continuous math becomes Ax = b, and why iterative solvers matter (direct methods are O(n^3), CG is O(n*sqrt(kappa))).
MTL5 features demonstrated:
- dense2D construction of the discretization matrix
- dense_vector for solution and RHS
- itl::cg() with noisy_iteration to watch convergence
- itl::pc::diagonal preconditioner vs itl::pc::identity (no preconditioner)
- Comparison: how many iterations with/without diagonal preconditioning
Program: examples/phase03_iterative_solvers/heat_equation_1d.cpp
Loading the trace…
Left: the temperature u(x) along the rod after each CG step, starting from u = 0. The conductivity rises from 1 at the left end to 100 at the right, so heat leaves the left half slowly and the hottest point sits at x ≈ 0.21, not in the middle. Right: the true residual ‖b − A u‖ / ‖b‖ of each run, on a log axis.
Without a preconditioner CG takes 145 steps to reach 1e-10; with diag(A) as the preconditioner it takes 100. There are n = 100 unknowns, and the diagonal varies by a factor of 50. The two answers differ by 1.07e-16. Neither residual falls steadily: they rise to 9.8 and 4.4 times their starting value first, because CG minimizes the error in the A-norm, not the residual. The preconditioned run is still at 0.34 ten steps before the end, then reaches 1.3e-12 at step n = 100, as CG does in exact arithmetic.
Example 3B: Convection-Diffusion: When Symmetry Breaks
Section titled “Example 3B: Convection-Diffusion: When Symmetry Breaks”Numerical goal: Solve -epsilon * u”(x) + u’(x) = f(x) (convection-diffusion) with central differences. The upwind convection term makes the matrix non-symmetric, so CG cannot be used — this motivates BiCGSTAB.
Demonstrates why we need different solvers. We first try CG, which will fail or diverge, then switch to BiCGSTAB, which is able to solve this system of equations. Shows iteration control:
- basic_iteration for silent runs,
- noisy_iteration for debugging,
- cyclic_iteration for periodic residual checks.
MTL5 features demonstrated:
- Non-symmetric dense system construction
- itl::cg() fails (or converges erratically) — demonstrates solver applicability limits
- itl::bicgstab() succeeds on the same problem
- All three iteration controllers: basic_iteration, noisy_iteration, cyclic_iteration
- itl::pc::diagonal preconditioner
Program: examples/phase03_iterative_solvers/convection_diffusion.cpp
Loading the trace…
Left: u(x) after each step of CG and of BiCGSTAB, with the exact solution of −εu″ + u′ = 1 dashed. The exact solution is nearly the line u = x, and it drops to zero in a boundary layer of width about ε at x = 1. Right: each solver's true residual on a log axis. Choose ε to change the problem.
On n = 30 points BiCGSTAB converges at every ε, in 30 steps at ε = 1 and 64 at ε = 0.01. CG stops at its 500-step limit every time. At ε = 1 the matrix is nearly symmetric and CG gets close, to a residual of 1.5e-8. At ε = 0.01 its relative residual ends at 2440, far above the 1 it started from. The animation shows CG's first 128 steps. At ε = 0.01 the cell Péclet number h/(2ε) is 1.61, above 1, so the central differences themselves oscillate: the converged discrete solution overshoots to 1.2 next to the layer and is 0.27 away from the exact curve. That error is the discretization's, not the solver's.
Phase 4: Sparse Matrices, Inserter, GMRES, BiCG, Smoothers
Section titled “Phase 4: Sparse Matrices, Inserter, GMRES, BiCG, Smoothers”Example 4A: 2D Laplacian on a Grid (Sparse Assembly + GMRES)
Section titled “Example 4A: 2D Laplacian on a Grid (Sparse Assembly + GMRES)”Numerical goal: Solve the 2D Poisson equation, -Δu = f, on the unit square using a 5-point stencil finite difference scheme. This produces a large, sparse, banded SPD system. Assembly via the inserter pattern demonstrates real-world sparse matrix construction.
The 2D Laplacian is the canonical sparse systems benchmark (Saad, “Iterative Methods for Sparse Linear Systems”). Students see how the inserter builds CSR row-by-row, why sparse storage matters (a 100x100 grid = 10,000 unknowns but only ~50,000 nonzeros vs 10^8 dense entries), and how GMRES handles this.
MTL5 features demonstrated:
- compressed2D with inserter + update_store for 5-point stencil assembly
- Grid-to-linear index mapping
- itl::gmres() with restart parameter (compare restart=10 vs restart=30)
- itl::cg() as comparison (valid since the 2D Laplacian is SPD)
- itl::pc::diagonal preconditioning
- noisy_iteration showing convergence history
Program: examples/phase04_sparse_assembly/laplacian_2d.cpp
Loading the trace…
The first 10 frames fill the 100 × 100 matrix of a 10 × 10 grid, one grid row (10 matrix rows) at a time: five entries per row, fewer at the boundary, 460 in all. Then the left panel shows the GMRES(5) and GMRES(20) iterates as heat maps on the grid, and the right panel each solver's true residual on a log axis.
GMRES(20) and CG converge in 15 and 15 steps, and GMRES(5) in 85. Up to step 5 the two GMRES runs are the same method. GMRES(5) then restarts, throws away its Krylov basis, and slows: at step 6 its residual is 0.21 against 0.15 for GMRES(20). Each restart, marked on the axis, is a kink in its curve. The three answers agree to 5.9e-10.
Example 4B: Stationary Iteration: Smoothers as Standalone Solvers
Section titled “Example 4B: Stationary Iteration: Smoothers as Standalone Solvers”Numerical goal: Solve a small diagonally-dominant system using classical iterative methods (Jacobi, Gauss-Seidel, SOR) and study convergence rates. Demonstrates the spectral radius concept: Jacobi < Gauss-Seidel < SOR(optimal omega).
Directly from Golub & Van Loan, Chapter 10, and Saad, Chapter 4. We see that smoothers are solvers, albeit slow ones, motivating why they’re used as building blocks in multigrid. The SOR omega sweep is a classic homework exercise made interactive.
MTL5 features demonstrated:
- compressed2D with inserter for a diagonally-dominant sparse system
- itl::smoother::jacobi, itl::smoother::gauss_seidel, itl::smoother::sor
- Residual reduction tracking over multiple sweeps
- SOR with varying omega (0.5, 1.0, 1.2, 1.5, optimal) — tabulated convergence comparison
- Sparse vs dense specialization (same API, different performance)
Program: examples/phase04_sparse_assembly/smoother_convergence.cpp
Loading the trace…
Top left: the error after each sweep, starting from the exact discrete solution plus a smooth error (mode 1) and an oscillatory one (mode 40 of 50). Bottom left: the two modes' amplitudes, solid for mode 1, dashed for mode 40. Top right: the residual of each method from x = 0. Bottom right: SOR's residual after 100 sweeps for each ω, which does not change from frame to frame.
Gauss-Seidel cuts mode 40 from 0.02 to 3.9e-7 in 10 sweeps, while mode 1 only goes from 0.02 to 0.0192. Undamped Jacobi flips mode 40's sign every sweep and shrinks it more slowly. That is why these methods are smoothers: a coarser grid sees the smooth error as oscillatory, which is multigrid's idea. As solvers on their own they are slow: after 100 sweeps the residual is 0.754 for Jacobi and 0.623 for Gauss-Seidel. SOR at ω = 2/(1 + sin πh) = 1.884 reaches 3e-4, and the ω sweep's smallest residual is at ω = 1.884.
Phase 5: Direct Factorizations (LU, QR, LQ, Cholesky, Triangular Solvers, ILU/IC)
Section titled “Phase 5: Direct Factorizations (LU, QR, LQ, Cholesky, Triangular Solvers, ILU/IC)”Example 5A: Least Squares Curve Fitting via QR
Numerical goal: Fit a polynomial to noisy data points using the overdetermined system Vc = y, where V is a Vandermonde matrix. Compare normal equations (V^T V c = V^T y via Cholesky) vs. QR factorization—demonstrating why QR is numerically superior.
This is Trefethen & Bau Lecture 11 and Golub & Van Loan Section 5.3. The Vandermonde matrix is notoriously ill-conditioned, making it a perfect stress test. We see the normal equations give incorrect answers at high polynomial degree while QR remains stable.
MTL5 features demonstrated:
- dense2D Vandermonde matrix construction
- qr_factor() + qr_extract_Q/R() for QR factorization
- cholesky() for normal equations approach
- upper_trisolve() / lower_trisolve() for back-substitution
- trans() view for V^T * V
- Side-by-side numerical comparison showing conditioning effects
Program: examples/phase05_dense_decompositions/least_squares_qr.cpp
Loading the trace…
Left: the 20 data points, sin x plus a small deterministic perturbation, and the fitted polynomial of each degree. Top right: the residual ‖y − Vc‖ of each method. Bottom right: cond(V) from V's singular values (grey), its square, which is what the normal equations face, and cond(VᵀV) as the example estimates it, from the eigenvalues of the computed VᵀV (dashed).
The two methods' residuals agree to six digits up to degree 9. Past that, the normal equations' residual stalls between 3e-5 and 1.2e-4 up to degree 14, while QR's keeps falling, to 1.2e-10 at degree 18. From degree 15 on, Cholesky stops at a non-positive pivot: VᵀV is no longer positive definite in floating point. Its true condition number, cond(V)², is 3.2e35 at degree 18. The eigenvalue estimate never exceeds 1.4e22, because the smallest computed eigenvalue is rounding noise. The curves themselves look alike: both fits pass close to the points, and the difference is in the digits.
Example 5B: Solving Ax=b Three Ways: LU vs Cholesky vs QR
Section titled “Example 5B: Solving Ax=b Three Ways: LU vs Cholesky vs QR”Numerical goal: Given a well-conditioned SPD system, solve it using LU (general), Cholesky (SPD-exploiting), and QR (orthogonal). Compare operation counts,
accuracy, and applicability. Then show a non-SPD system where Cholesky fails but LU/QR work, and sweep the Hilbert matrix, where the
explicit inverse loses to all three factorizations. The test matrices come from MTL5’s generators: lehmer, wilkinson, hilbert
and laplacian_1d.
Directly addresses the “which factorization when?” question from Golub & Van Loan Chapter 3-5. We build intuition for the factorization decision tree that every practicing numerical analyst uses.
MTL5 features demonstrated:
- lu_factor() + lu_solve() (with partial pivoting)
- cholesky_factor() + cholesky_solve()
- qr_factor() + qr_solve()
- inv() as the “never do this in practice” baseline
- condition_number() and eigenvalue_symmetric() to show why each matrix behaves as it does
- ILU(0) and IC(0) as approximate factorizations for preconditioning preview
Program: examples/phase05_dense_decompositions/solve_three_ways.cpp
Loading the trace…
Each step finishes one column. LU (with partial pivoting) leaves a row of U and a column of multipliers,
and swaps rows to bring the largest pivot up. Cholesky leaves a column of L and works only on the lower
triangle. QR applies one Householder reflection, which zeroes the column below the diagonal. The unshaded
block is what is left to eliminate. The intermediate matrices are rebuilt from the factors that MTL5's
lu_factor, cholesky_factor and qr_factor return. The flop counts are the
textbook ones.
The SPD matrix is generators::lehmer(4), L(i, j) = (min(i, j) + 1) / (max(i, j) + 1). On it the three take 34, 30 and 110 flops.
At n = 4 the lower-order terms dominate; at n = 1000 the same counts give 6.66e8,
3.34e8 and 1.33e9, the 2 : 1 : 4 of 2n³/3, n³/3 and 4n³/3. The indefinite
matrix is Wilkinson's W₄⁺, generators::wilkinson(4): symmetric tridiagonal, with one negative eigenvalue.
LU and QR finish, but Cholesky's pivot at step 2 is -0.167. It would need its
square root, so cholesky_factor returns 2.
Loading the trace…
Part 3 of the program solves H x = b for x = (1, …, 1), with H(i, j) = 1 / (i + j + 1), for n = 4 to 15. Left: the backward error ‖b − Hx̂‖ / (‖H‖ ‖x̂‖), how well each method solved the system it was given. Right: the forward error ‖x̂ − x‖ / ‖x‖, how close it came to x. Both in the ∞-norm.
The three factorizations are backward stable: their backward error never exceeds 8.7e-16, about 4ε. The inverse's rises from 2.1e-13 at n = 4 to 6.4e-4 at n = 11. Every forward error grows with cond(H), because the problem itself is that sensitive; LU's stays below cond(H)·ε at 8 of the 8 orders where the SVD can still resolve cond(H), below 1e16. Cholesky fails from n = 13 on, though H is SPD: past cond(H) = 1/ε, H is positive definite only up to rounding. At n = 12, with cond(H) = 1.8e16, it still succeeds. The backward error is exactly 0, which a log axis cannot show, for Cholesky at n = 4 and 5.
Phase 6: Eigenvalue Solvers, SVD, Kronecker, Advanced Krylov
Section titled “Phase 6: Eigenvalue Solvers, SVD, Kronecker, Advanced Krylov”Example 6A: Vibrating String: Eigenvalues as Physical Frequencies
Section titled “Example 6A: Vibrating String: Eigenvalues as Physical Frequencies”Numerical goal: Compute the natural frequencies of a vibrating string by finding eigenvalues of the 1D Laplacian matrix. The eigenvalues are known analytically:
lambda_k = 4 sin^2(k*pi/(2n)),providing exact verification. Then extend to a 2D membrane using the Kronecker product.
Strang’s “Linear Algebra and Its Applications” Chapter 6 — eigenvalues as physical vibration modes is the most intuitive introduction to spectral methods. The Kronecker product for 2D is from Golub & Van Loan, Section 4.8.
MTL5 features demonstrated:
- eigenvalue_symmetric() on the tridiagonal Laplacian
- Verification against analytical eigenvalues
- kron() to build 2D Laplacian from 1D (I kron T + T kron I)
- eigenvalue() (general) on a non-symmetric perturbation showing complex eigenvalues
- svd() to verify singular values equal absolute eigenvalues for symmetric matrices
Program: examples/phase06_eigenvalue_svd/vibrating_string.cpp
Loading the trace…
The first 8 frames are the modes of the string: eigenvector k of the 8 × 8 Laplacian, vibrating while the frame plays at a speed proportional to √λ_k, so mode k oscillates √(λ_k/λ_1) times as fast as the fundamental. On the right, the computed λ_k sit on the analytic curve 4 sin²(kπ / 2(n+1)). They agree to the 12 digits the trace keeps; the example prints differences of a few units in the last place. The next 16 frames are the modes of a 4 × 4 membrane from kron(I, T) + kron(T, I), with positive and negative displacement in two colours. Where two modes share an eigenvalue, any mix of them is also a mode, and the picture shows the one MTL5 returned.
The last 16 frames make the string lopsided, the way convection does in example 3B: subdiagonal
−(1 + d), superdiagonal −(1 − d). The eigenvalues, 2 − 2√(1 − d²) cos(kπ/(n+1)), close in on 2 as d grows.
At d = 1 the matrix is triangular and all of them equal 2. From d = 1.1 on they leave the real
axis in conjugate pairs, and at d = 1.5 the largest imaginary part is
2.1. The rings mark the formula and the dots are MTL5's eigenvalue().
Example 6B: Principal Component Analysis (PCA) via SVD
Section titled “Example 6B: Principal Component Analysis (PCA) via SVD”Numerical goal: Perform PCA on a small dataset — compute SVD of the centered data matrix, extract principal components, and project data onto reduced dimensions. Compare with eigendecomposition of the covariance matrix.
PCA/SVD is ubiquitous in data science and appears in Trefethen & Bau Lecture 4-5. It makes the abstract SVD concrete: U gives sample coordinates, V gives feature loadings, Sigma gives variance explained. Two approaches (SVD of data vs eigendecomposition of covariance) connect Phase 5 and Phase 6.
MTL5 features demonstrated:
- svd() — U, S, V decomposition
- eigenvalue_symmetric() on X^T * X covariance matrix
- Dense matrix arithmetic: centering, trans(), and matrix multiplication
- Verification: U * diag(S) * V^T ≈ X
- Truncated reconstruction showing information loss
Program: examples/phase06_eigenvalue_svd/pca_svd.cpp
Loading the trace…
Left: the 8 samples, centered, in the plane of features 1 and 3, the two that were made to correlate. The arrows are the first two principal directions, the columns of V, drawn in that plane. The next frame moves every sample to its principal coordinates (PC1, PC2) = rows of Xc V. The last two take the data back to the feature plane, rebuilt from two components and then from one. Right: the share of the variance, σ_k² / Σσ², that each component carries.
The singular values are 9.132, 1.523, 0.2084, so the components explain 97.2%, 2.71%, 0.0506% of the variance. Rebuilt from two components the data is off by ‖Xc − X₂‖_F = 0.2084, which is σ₃; from one, by 1.538, which is √(σ₂² + σ₃²). No rank-r approximation does better (Eckart–Young). In the rank-1 frame every sample lies on the first principal direction.
Phase 7: Sparse Formats, Views & I/O
Section titled “Phase 7: Sparse Formats, Views & I/O”Example 7A: Sparse Format Shootout: CSR vs COO vs ELL
Section titled “Example 7A: Sparse Format Shootout: CSR vs COO vs ELL”Numerical goal: Build the same sparse matrix (2D Laplacian) in three formats:
- coordinate (COO for assembly),
- compressed (CSR for computation), and
- ELLPACK (ELL for GPU-like access patterns).
Compare storage costs and access patterns. Then write/read the matrix via Matrix Market format.
Saad Chapter 3 “Sparse Matrix Computations” — understanding sparse formats is a prerequisite to efficient large-scale computing. We see that format choice depends on the operation (assembly → COO, matvec → CSR/ELL, I/O → Matrix Market).
MTL5 features demonstrated:
- coordinate2D with insert(), sort(), compress() pipeline
- compressed2D with inserter
- ell_matrix constructed from compressed2D
- io::mm_write_sparse() and io::mm_read() round-trip
- Storage comparison: bytes per format for same matrix
- Element access correctness verification across all three
Program: examples/phase07_sparse_formats/sparse_formats.cpp
Loading the trace…
Each frame is one row of y = A x on the 36 × 36 Laplacian of a 6 × 6 grid.
Left: the row in the matrix, and the entries of x it needs. Right: the memory each format reads for it. The
sorted COO triplets keep the row together, but finding it needs a search or a scan. CRS jumps straight there
through row_ptr. ELL computes the address, row × width, and reads every slot, the padding too.
All three hold the same 156 nonzeros. Counted in stored values, as the example's table does: dense 1296, COO 468 (row, column and value per entry), CRS 349 (values, columns and 37 row pointers), ELL 360 (36 rows × 5 slots, two arrays, 24 of the slots padding). ELL pays for padding with addresses it can compute, which suits SIMD and GPU kernels that process rows in lockstep.
Example 7B: Structured Matrix Views: Exploiting Symmetry and Bandedness
Section titled “Example 7B: Structured Matrix Views: Exploiting Symmetry and Bandedness”Numerical goal: Start with a full dense matrix from a finite element assembly, then demonstrate how views reduce storage and computation. Show:
- Hermitian view stores only the upper triangle,
- banded view extracts tridiagonal structure,
- map view extracts a subproblem.
Apply CG to the Hermitian-viewed matrix.
Views are a key abstraction in modern matrix libraries (MATLAB’s triu, band; Julia’s Symmetric, view). Students learn that you don’t always need to copy/transform data — views provide zero-cost abstractions. Golub & Van Loan Section 1.2.7 on exploiting structure.
MTL5 features demonstrated:
- hermitian() view of an upper-triangular stored matrix
- banded() view with different bandwidth parameters
- mapped() for submatrix extraction and row permutation
- identity2D as implicit identity (no storage)
- Combining views with solvers: CG on hermitian_view
- Matrix Market I/O to save/load results
Program: examples/phase07_sparse_formats/structured_views.cpp
Loading the trace…
Left: the stored matrix: the upper triangle for the Hermitian view, the full matrix for the others. Right: the view, as MTL5 returns it. Each step shows one view and marks the stored entries it reads. A view that reads an entry for two of its cells (the Hermitian view's mirror) marks it in the second colour. Cells a view computes without reading anything, such as a band's zeros or the identity, stay blank on the left.
The views store nothing. The Hermitian view's 36 cells read 21 stored entries, the upper
triangle, and tridiagonal band reads 16, diagonal reads 6, sub-matrix reads 9, rows reversed reads 36, identity reads 0. The last frames run CG
on hermitian(A_upper) as if it were a full matrix. It converges in 6 steps, to a
residual of 1.7e-16, without the lower triangle ever being stored.