Foundations 5: Projecting and Solving the 1D System

Back to regularizeNd series home

Previous: Foundations 4: From Equations to Efficient Code

Prerequisites: Foundations 1: Fidelity Equations, Foundations 2: Smoothness and Least Squares, Foundations 3: Normalization and Residuals, and Foundations 4: From Equations to Efficient Code.

Learning goals

NoteSource and attribution

This page is adapted from “RegularizeData2D, the Excel Spreadsheet Function for Regularizing 2D Data – Part 2 of 2” by Peter Goldstein, published February 17, 2013 on Math for Mere Mortals (under the username kintaar): https://mathformeremortals.wordpress.com/2013/02/17/regularizedata2d-the-excel-spreadsheet-function-for-regularizing-2d-data-part-2-of-2/ (Goldstein 2013).

This page is an independent implementation and modernization of that article’s ideas for regularizeNd, not a transcription. Its text, equations, examples, numbers, and figures were written and computed for this site.

Foundations 4 assembled the fidelity block \(A_f\) and the scaled smoothness block \(L\) as sparse matrices, and showed that the normal matrix \(A^TA\) is banded and should be factored, never inverted. This page opens up that product: where each of its entries comes from, and how the banded system is then solved.

The example is the series fixture: five samples at \(x=[0.35,\ 1.00,\ 1.80,\ 2.70,\ 3.65]\) with values \(y=[1.0,\ 1.4,\ 0.4,\ 1.2,\ 0.2]\), the six-node grid \(g=[0,\ 1,\ 2,\ 2.5,\ 3,\ 4]\), and smoothness \(s=0.01\), so the smoothness rows carry the multiplier \(m=0.1788854382\).

addpath('fixtures');
r = regularizeNdFoundationsFixtures(Verbose=false);
fx = r.oneD;  proj = fx.projection;
x = fx.x;  y = fx.y;  g = fx.grid;  s = fx.smoothness;
Af = fx.system.fidelity;            % 5-by-6
L = fx.system.regularization;       % 4-by-6, already scaled by m
m = fx.system.multiplier;
n = numel(g);  Nf = numel(x);  Ns = n - 2;

The normal equations as a sum of rows

Stack the blocks as before, \(A=\begin{bmatrix}A_f\\L\end{bmatrix}\) and \(b=\begin{bmatrix}y\\0\end{bmatrix}\), and write row \(k\) of \(A\) as \(a_k^T\). Entry \((i,j)\) of \(A^TA\) is the dot product of columns \(i\) and \(j\) of \(A\), which is a sum over rows:

\[ (A^TA)_{ij}=\sum_k A_{ki}A_{kj} \qquad\Longrightarrow\qquad A^TA=\sum_k a_k a_k^T, \qquad A^Tb=\sum_k b_k\,a_k . \]

Each row contributes one outer product to the matrix and one scaled copy of itself to the right-hand side. A row with nonzeros only in the column set \(c_k\) produces an outer product that is nonzero only in the block \(c_k\times c_k\). A fidelity row touches at most 2 columns, so it updates at most a \(2\times2\) block. A smoothness row touches 3, so it updates a \(3\times3\) block.

Splitting the sum by block gives the three pieces this page traces:

\[ A^TA = \underbrace{\sum_{\text{samples}} a_k a_k^T}_{A_f^TA_f} + \underbrace{\sum_{\text{smoothness rows}} a_k a_k^T}_{L^TL}, \qquad A^Tb = A_f^Ty + L^T0 = A_f^Ty . \]

The smoothness rows have a zero right-hand side, so they shape the matrix but never touch the right-hand side. Only the samples feed \(A^Tb\).

Tracing one fidelity row

Sample 3 sits at \(x=1.8\) with \(y=0.4\). It lies in the interval \([1,2]\), 0.8 of the way across, so its row of \(A_f\) has weight \(0.2\) on node 2 and \(0.8\) on node 3, and zeros elsewhere. Its two contributions are

\[ \begin{bmatrix}0.2\\0.8\end{bmatrix}\begin{bmatrix}0.2&0.8\end{bmatrix} =\begin{bmatrix}0.04&0.16\\0.16&0.64\end{bmatrix} \ \text{added to rows and columns 2–3 of } A_f^TA_f, \qquad 0.4\begin{bmatrix}0.2\\0.8\end{bmatrix}=\begin{bmatrix}0.08\\0.32\end{bmatrix} \ \text{added to entries 2–3 of } A_f^Ty . \]

Sample 2 is the exact-node case from Foundations 1. It sits on node 2, so its row has a single weight of 1. Its outer product is the \(1\times1\) block \([1]\), which adds 1 to the diagonal entry \((2,2)\), and it adds \(1.4\cdot1=1.4\) to entry 2 of \(A_f^Ty\). In general, a sample on node \(j\) has the row \(e_j^T\), and \(e_je_j^T\) is zero except at position \((j,j)\). Such a row changes only entry \((j,j)\) of \(A_f^TA_f\) and entry \(j\) of \(A_f^Ty\), and coincident samples on node \(j\) accumulate in those two places.

for k = [3 2]
    [~, c, w] = find(Af(k, :));
    fprintf('sample %d (x = %.2f, y = %.1f): columns %s, weights %s\n', ...
        k, x(k), y(k), mat2str(c), mat2str(full(w)))
    fprintf('  adds to Af''*Af(%s, %s):\n', mat2str(c), mat2str(c)); disp(full(w' * w))
    fprintf('  adds to Af''*y(%s): %s\n', mat2str(c), mat2str(full(y(k) * w)))
end
sample 3 (x = 1.80, y = 0.4): columns [2 3], weights [0.2 0.8]
  adds to Af'*Af([2 3], [2 3]):
    0.0400    0.1600
    0.1600    0.6400
  adds to Af'*y([2 3]): [0.08 0.32]
sample 2 (x = 1.00, y = 1.4): columns 2, weights 1
  adds to Af'*Af(2, 2):
     1
  adds to Af'*y(2): 1.4

Reading the sum the other way round, by entry instead of by row, shows how the pieces pile up. Node 2 is touched by three samples: sample 1 with weight \(0.35\), sample 2 with weight 1, and sample 3 with weight \(0.2\). So

\[ (A_f^TA_f)_{22}=0.35^2+1^2+0.2^2=1.1625,\qquad (A_f^Ty)_2=0.35\cdot1.0+1\cdot1.4+0.2\cdot0.4=1.83 . \]

shareOfDiagonal = full(Af(:, 2).^2)'   % each sample's share of (Af'*Af)(2,2)
shareOfRhs = full(Af(:, 2) .* y)'      % each sample's share of (Af'*y)(2)
shareOfDiagonal = 1×5 double
    0.1225    1.0000    0.0400         0         0
shareOfRhs = 1×5 double
    0.3500    1.4000    0.0800         0         0

Tracing one smoothness row

Smoothness row 2 is the second derivative at node 3 (\(g=2\)), using nodes 2, 3, and 4. Foundations 2 derived its unscaled weights on the uneven triple \((1,\ 2,\ 2.5)\): \([\tfrac43,\ -4,\ \tfrac83]\). Multiplying by \(m\) gives the row of \(L\),

\[ m\begin{bmatrix}\tfrac43&-4&\tfrac83\end{bmatrix}=\begin{bmatrix}0.238514&-0.715542&0.477028\end{bmatrix} \quad\text{on columns } 2,\,3,\,4 . \]

Its outer product is a full \(3\times3\) block, added to rows and columns 2–4 of \(L^TL\):

\[ \begin{bmatrix}0.0568889&-0.170667&0.113778\\-0.170667&0.512&-0.341333\\0.113778&-0.341333&0.227556\end{bmatrix}. \]

The block is symmetric, so only 6 of its 9 entries are distinct: the 3 on the diagonal and the 3 above it. An implementation can compute those 6 and mirror them. Every entry also carries the same factor \(m^2=0.032\), so the block is exactly \(0.032\) times the outer product of \([\tfrac43,\ -4,\ \tfrac83]\) with itself; for example, \(0.032\cdot16=0.512\). The row contributes nothing to \(A^Tb\).

[~, c, w] = find(L(2, :));
fprintf('columns %s\nunscaled weights %s\nscaled weights   %s\nm^2 = %.6f\n', ...
    mat2str(c), mat2str(full(fx.system.d2(2, c)), 6), mat2str(full(w), 6), m^2)
outerProduct = full(w' * w)
columns [2 3 4]
unscaled weights [1.33333 -4 2.66667]
scaled weights   [0.238514 -0.715542 0.477028]
m^2 = 0.032000
outerProduct = 3×3 double
    0.0569   -0.1707    0.1138
   -0.1707    0.5120   -0.3413
    0.1138   -0.3413    0.2276

The diagonal entry \((3,3)\) of \(L^TL\) shows the same piling up as before. Node 3 appears in smoothness rows 1, 2, and 3, with unscaled weights \(1\), \(-4\), and \(4\), so \((L^TL)_{33}=0.032\,(1+16+16)=0.032+0.512+0.512=1.056\). Row 2 supplies \(0.512\) of that total.

Accumulating every row

The cell below builds \(A_f^TA_f+L^TL\) and \(A_f^Ty\) the way a direct implementation would. It loops over the samples and computes each interpolation weight from \(x\) and the grid. Then it loops over the interior nodes and computes each scaled stencil from the spacings. Every row is added into a \(6\times6\) accumulator and then discarded. Neither \(A_f\), \(L\), nor \(A\) is used. (A large implementation would store only the band or collect sparse triplets, as Foundations 4 describes. A dense \(6\times6\) array keeps the bookkeeping visible here.)

Nacc = zeros(n);  AtyAcc = zeros(n, 1);

for k = 1:Nf                                  % fidelity rows
    j = min(find(g <= x(k), 1, 'last'), n - 1);
    t = (x(k) - g(j)) / (g(j+1) - g(j));
    c = [j, j+1];  w = [1 - t, t];
    c = c(w ~= 0);  w = w(w ~= 0);            % an on-node sample keeps one weight
    Nacc(c, c) = Nacc(c, c) + w' * w;
    AtyAcc(c) = AtyAcc(c) + y(k) * w';
end
fidelityPart = Nacc;

for j = 2:n-1                                 % smoothness rows, right-hand side 0
    hm = g(j) - g(j-1);  hp = g(j+1) - g(j);
    w = m * [2/(hm*(hm+hp)), -2/(hm*hp), 2/(hp*(hm+hp))];
    c = j-1:j+1;
    Nacc(c, c) = Nacc(c, c) + w' * w;
end
smoothnessPart = Nacc - fidelityPart;

Now compare with the explicit sparse products Af'*Af, L'*L, and Af'*y:

N = Af'*Af + L'*L;
Aty = Af'*y;
accumulatedVsExplicit = [max(abs(fidelityPart - Af'*Af), [], 'all'), ...
                         max(abs(smoothnessPart - L'*L), [], 'all'), ...
                         max(abs(Nacc - N), [], 'all'), ...
                         max(abs(AtyAcc - Aty))];
fprintf('max |accumulated - explicit|: Af''Af %.2g, L''L %.2g, N %.2g, Af''y %.2g\n', ...
    full(accumulatedVsExplicit))
fprintf('fixture''s own accumulation check: N %.2g, right-hand side %g\n', ...
    proj.accumulationDifference, proj.accumulationRhsDifference)
max |accumulated - explicit|: Af'Af 0, L'L 4.4e-16, N 4.4e-16, Af'y 0
fixture's own accumulation check: N 4.4e-16, right-hand side 0

The two routes agree to round-off. The fixture runs the same comparison with its own loop and records a matrix difference of \(4.4\times10^{-16}\) and a right-hand-side difference of exactly 0. Summing products in a different order can change the last bit, which is all the matrix difference is.

The finished normal equations \(Nz=A_f^Ty\), with \(N=A_f^TA_f+L^TL\), are

\[ N\approx\begin{bmatrix} 0.4545&0.1635&0.032&0&0&0\\ 0.1635&1.347389&-0.074667&0.113778&0&0\\ 0.032&-0.074667&1.696&-1.365333&0.512&0\\ 0&0.113778&-1.365333&2.863111&-1.125333&0.113778\\ 0&0&0.512&-1.125333&1.3065&0.056833\\ 0&0&0&0.113778&0.056833&0.479389 \end{bmatrix}, \qquad A_f^Ty=\begin{bmatrix}0.65\\1.83\\0.32\\0.72\\0.55\\0.13\end{bmatrix}. \]

close all
figure('Position', [100 100 1100 380])
parts = {full(Af'*Af), full(L'*L), full(N)};
names = {'A_f^TA_f (5 fidelity rows)', 'L^TL (4 smoothness rows)', 'N = A_f^TA_f + L^TL'};
cmax = max(abs(full(N)), [], 'all');
cmap = interp1([-1 0 1], [0.13 0.40 0.75; 1 1 1; 0.80 0.20 0.15], linspace(-1, 1, 255));
tiledlayout(1, 3, 'TileSpacing', 'compact');
for p = 1:3
    nexttile
    imagesc(parts{p}); axis square; clim([-cmax cmax]); colormap(cmap)
    [rr, cc] = find(parts{p});
    for q = 1:numel(rr)
        text(cc(q), rr(q), sprintf('%.4g', parts{p}(rr(q), cc(q))), ...
            'HorizontalAlignment', 'center', 'FontSize', 7)
    end
    title(names{p}); xlabel('column (grid node)'); ylabel('row (grid node)')
    xticks(1:n); yticks(1:n)
end
cb = colorbar; cb.Layout.Tile = 'east'; cb.Label.String = 'entry value';

The two parts of the normal matrix and their sum, each entry labelled with its value. Fidelity rows fill only blocks next to the diagonal; smoothness rows reach two places from it. Entries no row touched stay exactly zero (white).

The fidelity part splits into two separate blocks. No sample falls between nodes 3 and 4, so no fidelity row couples them, and entry \((3,4)\) of \(A_f^TA_f\) is zero. The smoothness rows fill that gap. Together, \(A_f\) and \(L\) give \(A\) full column rank, so \(N\) is positive definite even though \(A_f\) alone has rank 5. The sum has bandwidth 2, the pentadiagonal shape Foundations 2 predicted.

Solving with a banded Cholesky factor

\(N\) is symmetric positive definite, so it has a Cholesky factorization \(N=R^TR\) with \(R\) upper triangular. Solving \(Nz=A_f^Ty\) then takes two triangular solves and no inverse:

\[ R^Tv=A_f^Ty\quad\text{(forward substitution)},\qquad Rz=v\quad\text{(back substitution)} . \]

A Cholesky factor of a banded matrix stays inside the band, so \(R\) has nonzeros only on its diagonal and the two diagonals above it, with no fill (Foundations 4 plots both patterns). Each substitution step therefore uses at most two previously computed values. The loops below exploit that.

R = chol(N);                           % upper triangular, N = R'*R
[ri, rj] = find(R);
choleskyUpperBandwidth = max(rj - ri)

bw = 2;
v = zeros(n, 1);                       % forward substitution: R'*v = Af'*y
for i = 1:n
    k = max(1, i-bw):i-1;
    v(i) = (Aty(i) - full(R(k, i))' * v(k)) / R(i, i);
end
zChol = zeros(n, 1);                   % back substitution: R*z = v
for i = n:-1:1
    k = i+1:min(n, i+bw);
    zChol(i) = (v(i) - full(R(i, k)) * zChol(k)) / R(i, i);
end
choleskyUpperBandwidth = 2

To check the answer, solve the same least-squares problem a different way: QR on the stacked \(9\times6\) matrix \(A\), which never forms \(A^TA\). MATLAB’s sparse qr(A, b, "econ") returns the triangular factor \(R_{qr}\) and the product \(Q^Tb\) without returning \(Q\); one back substitution finishes the solve. The table also includes A\b and the fixture’s solution.

A = [Af; L];
b = [y; zeros(Ns, 1)];
[QTb, Rqr] = qr(A, b, "econ");
zQR = Rqr \ QTb;
zBackslash = A \ b;

differences = table(max(abs(zChol - zQR)), max(abs(zChol - zBackslash)), ...
    max(abs(zChol - fx.system.solution)), proj.choleskyDifference, ...
    VariableNames=["Cholesky vs qr", "Cholesky vs A\b", "Cholesky vs fixture", "fixture's own check"])
table(g, zChol, VariableNames=["node g", "z"])
differences = 1×4 table
Cholesky vs qr Cholesky vs A\b Cholesky vs fixture fixture's own check
4.4409e-16 6.6613e-16 6.6613e-16 6.6613e-16
ans = 6×2 table
node g z
0 0.9508
1 1.2046
2 0.6536
2.5000 0.8810
3 0.9258
4 -0.0477

All the routes agree to round-off, and the fixture’s own Cholesky-versus-QR check records \(6.7\times10^{-16}\). The fitted table is

\[ z \approx [0.950780,\ 1.204629,\ 0.653552,\ 0.881039,\ 0.925797,\ -0.047683]^T , \]

the same compromise between fidelity and smoothness that Foundations 2 and 3 found. It does not pass through the samples.

The two factorizations are closer than they look. Since \(A^TA=R_{qr}^TQ^TQR_{qr}=R_{qr}^TR_{qr}\), the QR factor is also a Cholesky factor of \(N\); up to the signs of its rows it is the same matrix \(R\). QR reaches it from \(A\) without ever forming \(A^TA\), and that difference is what the next section is about.

The price of the normal equations

The normal-equation route is compact and keeps the band, but it has a known numerical cost. For a matrix \(A\) with full column rank, the 2-norm condition number satisfies

\[ \kappa_2(A^TA)=\kappa_2(A)^2 , \]

because the singular values of \(A^TA\) are the squares of those of \(A\). The condition number bounds how much relative rounding error can be amplified in a solve. Solving through \(A^TA\) can therefore lose about twice as many digits as a method, such as QR, that works on \(A\) directly.

For the fixture the system is very well conditioned:

kappaA = cond(full(A));
kappaN = cond(full(N));
fprintf('kappa(A) = %.6f, kappa(A''A) = %.6f, kappa(A)^2 = %.6f, relative gap %.1g\n', ...
    kappaA, kappaN, kappaA^2, abs(kappaN - kappaA^2) / kappaA^2)
kappa(A) = 3.193570, kappa(A'A) = 10.198891, kappa(A)^2 = 10.198891, relative gap 0

Here \(\kappa_2(A)\approx3.19\) and \(\kappa_2(A^TA)\approx10.20\), so squaring costs nothing that matters. That changes as \(s\) shrinks, and, as the next subsection shows, as the grid is refined. Recall from Foundations 1 that \(A_f\) alone has rank 5: one direction in \(z\) is invisible to the samples, and only the smoothness rows pin it down. Their weight is proportional to \(s\), so the smallest singular value of \(A\) shrinks in proportion to \(s\), and \(\kappa_2(A)\) grows like \(1/s\). The sweep below rebuilds \(L\) for each \(s\) with the Foundations 2 formulas and computes both condition numbers.

stencil = @(gl, gc, gr) [2./((gc-gl).*(gr-gl)), -2./((gc-gl).*(gr-gc)), 2./((gr-gc).*(gr-gl))];
secondDiff = @(g) sparse(repmat((1:numel(g)-2)', 1, 3), (1:numel(g)-2)' + (0:2), ...
    stencil(g(1:end-2), g(2:end-1), g(3:end)), numel(g)-2, numel(g));
smoothnessBlock = @(g, s) s * sqrt(Nf/(numel(g)-2)) * (g(end)-g(1))^2 * secondDiff(g);
assert(max(abs(smoothnessBlock(g, s) - L), [], 'all') < 1e-14)

sSweep = 10.^(-8:0.25:1);
kappaASweep = zeros(size(sSweep));  kappaNSweep = kappaASweep;  normalVsQR = kappaASweep;
for k = 1:numel(sSweep)
    As = [Af; smoothnessBlock(g, sSweep(k))];
    kappaASweep(k) = cond(full(As));
    kappaNSweep(k) = cond(full(As'*As));
    normalVsQR(k) = max(abs((As'*As) \ (As'*b) - As \ b));
end
decades = ismember(round(4*log10(sSweep)), 4*(-8:2:0));
table(sSweep(decades)', kappaASweep(decades)', kappaNSweep(decades)', normalVsQR(decades)', ...
    VariableNames=["s", "kappa(A)", "kappa(A'A)", "max |z_normal - z_QR|"])
ans = 5×4 table
s kappa(A) kappa(A'A) max |z_normal - z_QR|
1.0000e-08 7.1941e+05 5.1755e+11 1.3626e-05
1.0000e-06 7.1941e+03 5.1755e+07 5.1577e-09
1.0000e-04 71.9510 5.1769e+03 1.4677e-13
0.0100 3.1936 10.1989 4.4409e-16
1 253.4041 6.4214e+04 5.8509e-13
figure
loglog(sSweep, kappaASweep, '-o', 'LineWidth', 1.5, 'MarkerSize', 4, 'DisplayName', '\kappa_2(A)')
hold on; grid on
loglog(sSweep, kappaNSweep, '-s', 'LineWidth', 1.5, 'MarkerSize', 4, 'DisplayName', '\kappa_2(A^TA)')
loglog(sSweep, kappaASweep.^2, 'k:', 'LineWidth', 1.5, 'DisplayName', '\kappa_2(A)^2')
xline(0.01, ':', 's = 0.01', 'Color', [0.4 0.4 0.4], 'HandleVisibility', 'off')
xlabel('smoothness s'); ylabel('2-norm condition number')
title('Conditioning of the fixture system')
legend('Location', 'north')

Condition numbers of the stacked matrix A and of the normal matrix A^TA for the fixture, as the smoothness value s varies. The normal matrix’s condition number equals the square of A’s, to within rounding, at every s shown. The vertical dotted line marks the default s = 0.01 used on this page.

Below \(s=10^{-3}\), each tenfold decrease in \(s\) multiplies \(\kappa_2(A)\) by about 10 and \(\kappa_2(A^TA)\) by about 100. At \(s=10^{-8}\), \(\kappa_2(A^TA)\) is about \(5\times10^{11}\). The last column of the table shows the effect: at the default the two solves agree to round-off, but at \(s=10^{-8}\) they differ by roughly \(10^{-5}\). The exact digits depend on the factorization MATLAB picks, but the size is far above round-off and consistent with the bound \(\kappa_2(A^TA)\,\varepsilon\approx10^{-4}\), where \(\varepsilon\) is the machine epsilon. The condition number also rises for large \(s\), where the table is pressed toward the straight lines that \(L\) cannot see. This six-unknown system is tiny, so even the worst case here keeps several digits; the point is the trend, not the specific numbers.

Refining the grid

A small \(s\) is not the only way to lose conditioning. Refining the grid while the samples stay the same does it too, for two reasons. Every new node adds an unknown, but five samples can never see more than five directions in \(z\), so each added direction is held in place only by the smoothness rows. And the smoothness weights grow as the spacing \(h\) shrinks. The unscaled second-derivative stencil grows like \(1/h^2\); the rows of \(L\) also carry the factor \(\sqrt{N_f/N_s}\) from Foundations 3, which shrinks like \(h^{1/2}\), so their entries grow about like \(h^{-3/2}\). Either way they grow, while a fidelity weight never exceeds 1. The cell below splits every interval of the fixture grid into 16, 128, and 2000 equal pieces, rebuilds \(A_f\) with the Foundations 1 interpolation weights and \(L\) with the Foundations 2 formulas, keeps \(s=0.01\), and solves both ways. For these larger matrices it uses condest, MATLAB’s inexpensive estimate of the 1-norm condition number, in place of cond.

lowerNode = @(g) min(discretize(x, g), numel(g) - 1);   % interval holding each sample
frac = @(g, j) (x - g(j)) ./ (g(j+1) - g(j));
fidelityBlock = @(g) sparse(repmat((1:Nf)', 1, 2), lowerNode(g) + [0 1], ...
    [1 - frac(g, lowerNode(g)), frac(g, lowerNode(g))], Nf, numel(g));
assert(isequal(fidelityBlock(g), Af))

piecesPerInterval = [1 16 128 2000];
nodes = zeros(size(piecesPerInterval));
[rankAf, maxWeightL, condestN, gapRefined] = deal(nodes);
lastwarn('')
for k = 1:numel(piecesPerInterval)
    pieces = arrayfun(@(q) linspace(g(q), g(q+1), piecesPerInterval(k) + 1)', 1:n-1, UniformOutput=false);
    gk = unique(vertcat(pieces{:}));
    Afk = fidelityBlock(gk);  Lk = smoothnessBlock(gk, s);
    Ak = [Afk; Lk];  bk = [y; zeros(numel(gk) - 2, 1)];
    nodes(k) = numel(gk);
    rankAf(k) = rank(full(Afk));
    maxWeightL(k) = full(max(abs(Lk), [], 'all'));
    condestN(k) = condest(Ak'*Ak);
    gapRefined(k) = max(abs((Ak'*Ak) \ (Ak'*bk) - Ak \ bk));
end
table(nodes', rankAf', maxWeightL', condestN', gapRefined', ...
    VariableNames=["nodes", "rank(A_f)", "largest |L| weight", "condest(A'A)", "max |z_normal - z_QR|"])
warningText = lastwarn
ans = 4×5 table
nodes rank(A_f) largest |L| weight condest(A'A) max |z_normal - z_QR|
6 5 1.4311 15.7206 4.4409e-16
81 5 82.4369 7.5293e+05 6.7447e-12
641 5 1.8551e+03 3.0398e+09 6.7378e-08
10001 5 1.1449e+05 1.8070e+14 8.0447e-04
warningText =
  0×0 empty char array

The fidelity block stays at rank 5 however many nodes there are, while the largest smoothness weight grows by orders of magnitude. Going from 6 to 81 nodes makes every interval 16 times finer and multiplies that weight by about 57.6, close to \(16^{3/2}=64\) and well short of the \(16^2=256\) of the unscaled stencil. At the same \(s=0.01\), the condition estimate climbs from about \(10^6\) at 81 nodes to about \(3\times10^9\) at 641 nodes and about \(2\times10^{14}\) at 10,001 nodes, and the gap between the normal and QR solves grows with it, to roughly \(10^{-3}\) on the finest grid. MATLAB issued no warning for any of these solves: lastwarn is still empty. Conditioning worsens with node count as well as with small \(s\), and nothing on screen says so.

This is why regularizeNd’s help text treats 'normal' as a first guess rather than a rule. At the pinned revision it says that the equations regularizeNd generates tend to be well conditioned, but also that '\' may be best for ill-conditioned problems, that you should switch to '\' if 'normal' gives rank-deficiency warnings, and that 'normal' should be used with care when the smoothness value is small, because that makes the equations less well conditioned. The help text links the number of grid points to solve time, not to conditioning, and the refinement above shows that waiting for a warning is not enough. When the grid has far more nodes than there are samples, or \(s\) is small, compare against '\' even if MATLAB stays quiet. The deep dive’s Solving section lists a large number of grid points among the risks and covers how regularizeNd chooses among its solvers. The normal-equation route is regularizeNd’s default implementation choice; it is not a universal recommendation for least squares.

Connection to regularizeNd

regularizeNd does not loop over rows the way this page does. It builds the sparse blocks with regularizeNdMatrices and stacks them into \(A\). Its default 'normal' route then forms A'*A and A'*[y;0] with sparse matrix products and solves with backslash; Foundations 4 shows that code.

A'*A is exactly \(N=A_f^TA_f+L^TL\), and A'*[y;0] is exactly \(A_f^Ty\), the quantities accumulated above. The backslash then hands the sparse symmetric matrix to MATLAB, which solves it with a sparse factorization of its own choosing; no inverse is formed. This page’s explicit Cholesky solve is one valid way to do that step, not a description of MATLAB’s internals. The '\' solver applies backslash to the rectangular \(A\) instead, the QR route compared above.

The iterative solvers reuse the same projection. For 'pcg' and 'symmlq', regularizeNd forms AA = A'*A and d = A'*[y;...] and passes them to MATLAB’s pcg or symmlq, with an incomplete-Cholesky preconditioner built from AA when one can be computed. Only 'lsqr' iterates on the rectangular \(A\) itself, although its preconditioner is still computed from A'*A.

The regularizeNd package is not run on this page. The fixture reproduces its matrices and solution; its package cross-check agreed to \(8.88\times10^{-16}\).

How this differs from the original

  • Same projection. Like this page, the original splits \(A\) into a fidelity part and a derivative part, loops over the input points, and adds each point’s contributions into the right-hand side and the normal matrix in the same loop. How the original stores that matrix, and how it differs from regularizeNd’s sparse products, is covered in Foundations 4.
  • Symmetry in the outer products. The original also adds each derivative row’s outer product and computes only 6 of its 9 entries, mirroring the rest. That is the same symmetry saving described above.
  • Solver. Both routes end with an upper-triangular matrix and back substitution. The original gets there by Gaussian elimination on its five-wide band storage, keeping all five band entries of each row and eliminating the two to the left of the diagonal. This page’s Cholesky factorization uses the symmetry of \(N\) to store and update only one half of the band: in 1D, 3 of the 5 entries per row, the diagonal and the two to its right. Foundations 4 compares the solver strategies of the original and regularizeNd.
  • Conditioning. Neither RegularizeData2D article discusses the condition number of the normal equations. This page measures it, and regularizeNd offers QR and iterative solvers for the cases where it matters.
  • Example. The original walks through its own example. This page uses the series fixture, and every number on it is computed by the code above.
  • Terminology. The original calls one-input, one-output data “2D data”; this site follows regularizeNd and calls it 1D input.

On this page the 1D method became code: every row of the stacked system turned into a small update of the normal equations, and one banded Cholesky factor solved them. The next page leaves one input behind. It numbers the nodes of a 2D grid into a single vector and builds bilinear fidelity rows, which touch up to four columns instead of two.

Next

Back to regularizeNd series home

Previous: Foundations 4: From Equations to Efficient Code

Next: Foundations 6: Bilinear Interpolation and Grid Indexing

References

Goldstein, Peter. 2013. “RegularizeData2D, the Excel Spreadsheet Function for Regularizing 2D Data – Part 2 of 2.” Math for Mere Mortals. https://mathformeremortals.wordpress.com/2013/02/17/regularizedata2d-the-excel-spreadsheet-function-for-regularizing-2d-data-part-2-of-2/.