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.
Recap: the five-sample system
Foundations 1 and 2 built a complete least-squares problem for one input variable and one output. The original series calls this “2D data”; regularizeNd calls it a 1D input.
Samples:\(x=[0.35,\ 1.00,\ 1.80,\ 2.70,\ 3.65]\) and \(y=[1.0,\ 1.4,\ 0.4,\ 1.2,\ 0.2]\), so \(N_f=5\) fidelity rows.
The fidelity matrix \(A_f\) evaluates the linear interpolant of the six unknown table values \(z\) at the samples. The rows of \(D\) estimate the second derivative at the four interior nodes. The smoothness block is \(L=mD\) with the multiplier
where \(g_1\) and \(g_N\) are the first and last grid nodes, as in Foundations 2. The range factor uses the extent of the output grid, \(4-0\), not the spread of the samples.
Stacking the two blocks gives \(A=\begin{bmatrix}A_f\\L\end{bmatrix}\) and \(b=\begin{bmatrix}y\\0\end{bmatrix}\), and \(z\) minimizes \(\|Az-b\|_2^2\). This page uses the fixture shared by the whole series, which also recorded the solution.
addpath('fixtures');r=regularizeNdFoundationsFixtures(Verbose=false);fx=r.oneD;sys=fx.system;x=fx.x;y=fx.y;grid0=fx.grid;s=fx.smoothness;nF=numel(x);fprintf('multiplier m = %.10f\n',sys.multiplier)fprintf('solution z = [%s]\n',strjoin(compose('%.6f',sys.solution'),', '))
multiplier m = 0.1788854382
solution z = [0.950780, 1.204629, 0.653552, 0.881039, 0.925797, -0.047683]
Residuals of the solved fit
The residual vector \(Az-b\) has the same two blocks as \(A\):
\[
Az-b=\begin{bmatrix} A_f z - y \\ L z \end{bmatrix}
=\begin{bmatrix} r_f \\ r_s \end{bmatrix}.
\]
The fidelity residuals\(r_f\) are the fitted value at each sample minus the measured value. There is one per sample.
The smoothness residuals\(r_s = mDz\) are the scaled second derivatives of the table at the interior nodes. There is one per smoothness row. Their target is zero, because a straight line has zero curvature.
The fitted table (six nodes joined by straight lines, as linear interpolation reads them) and the five samples. Each orange segment is one fidelity residual: the gap between a sample and the curve directly above or below it.
The two residual groups of the solved system. Left: fidelity residuals, one per sample. Right: smoothness residuals, one per interior node, equal to the multiplier times the second difference there.
Reading the fidelity residuals. The fit is not an interpolant. The largest miss is \(0.363767\) at \(x=1.80\): the samples rise to \(1.4\), drop to \(0.4\), and rise again to \(1.2\), and following that zig-zag exactly would need large curvature. The fit gives up some fidelity there to keep the smoothness residuals small.
Reading the smoothness residuals. Their signs are the signs of the curve’s bending. The table has a crest near \(x=1\) (negative), a trough at \(x=2\) (positive), and bends down again at \(2.5\) and \(3\) (negative). The largest, at \(x=3\), is where the curve turns down toward the last sample.
The two groups balance exactly
A least-squares solution satisfies the normal equations \(A^T(Az-b)=0\). Split into the two blocks, they read
\[
A_f^T r_f = -L^T r_s .
\]
At every grid node, the pull of the samples on that table value is cancelled exactly by the pull of the curvature rows. That is the precise sense in which the solution balances fidelity against smoothness.
Two consequences follow, because each row of \(D\) gives zero on constant and on linear data. Multiply both sides by a vector of ones: the right side becomes \(-(L\mathbf 1)^T r_s = 0\), and since the rows of \(A_f\) sum to one, the left side is \(\sum_i r_{f,i}\). Multiply instead by the grid coordinates: linear interpolation reproduces \(x\) exactly, so the left side becomes \(x^T r_f\), and the right side is again zero. So
These are the same two conditions that the residuals of a least-squares straight line satisfy. The smoothness penalty never pulls on the mean or the trend of the data; it only removes bending.
Why each smoothness row is scaled by \(\sqrt{N_f/N_s}\)
Suppose the output grid is refined. The samples do not change, so there are still \(N_f=5\) fidelity rows. The number of smoothness rows, however, is \(N_s = n-2\) for \(n\) nodes, and it grows with every refinement.
Hold one smooth curve fixed and look at what its smoothness rows add up to. Each second-difference row estimates the curve’s second derivative at its node, \((Dz)_i \approx z''(x_i)\). A finer grid estimates the same second derivatives at more places, so with a multiplier \(c\) the smoothness sum of squares is roughly
where \(\overline{(z'')^2}\) is the average of \((z'')^2\) over the rows. Refining the grid leaves that average almost unchanged, so the sum grows in proportion to \(N_s\). Without a correction, a fourfold finer grid would count the same curvature four times as heavily, while the five fidelity rows stay as they were. The balance of the previous section would tip toward smoothness without anyone changing \(s\).
Multiplying each row by \(\sqrt{N_f/N_s}\) multiplies each squared residual by \(N_f/N_s\). The sum becomes \(c^2 N_f\,\overline{(z'')^2}\): the penalty now behaves as if there were exactly one smoothness row per sample, however many rows the grid actually has.
To check this numerically we need grids other than the fixture’s, so the next cell assembles the same equations for any grid. Each refinement inserts equally spaced points inside every interval of the original grid, so every refined grid still contains the original nodes.
% Insert f-1 equally spaced points inside every interval of g.refineGrid=@(g,f) interp1(0:numel(g)-1,g,linspace(0,numel(g)-1,f*(numel(g)-1) +1)');% Three-point second derivative on a nonuniform grid (Foundations 2).stencil=@(hL,hR) [2./(hL.*(hL+hR)),-2./(hL.*hR),2./(hR.*(hL+hR))];secondDiff=@(g) sparse(repmat((1:numel(g)-2)',1,3), (1:numel(g)-2)'+ (0:2),...stencil(diff(g(1:end-1)),diff(g(2:end))),numel(g) -2,numel(g));% Linear-interpolation fidelity rows (Foundations 1).leftNode=@(g,xs) min(sum(xs>=g',2),numel(g) -1);frac=@(g,xs,k) (xs-g(k)) ./ (g(k+1) -g(k));hatRows=@(g,xs,k) sparse(repmat((1:numel(xs))',1,2), [k,k+1],... [1-frac(g,xs,k),frac(g,xs,k)],numel(xs),numel(g));fidelityRows=@(g,xs) hatRows(g,xs,leftNode(g,xs));rowFactor=@(g) sqrt(nF/ (numel(g) -2));rangeFactor=@(g) (g(end) -g(1))^2;solveStacked=@(Af,L,yy) [Af;L] \ [yy;zeros(size(L,1),1)];% The helpers reproduce the fixture's system and solution.assert(max(abs(fidelityRows(grid0,x) -sys.fidelity), [],'all') <1e-14)assert(max(abs(secondDiff(grid0) -sys.d2), [],'all') <1e-12)zCheck=solveStacked(fidelityRows(grid0,x),s*rowFactor(grid0)*rangeFactor(grid0)*secondDiff(grid0),y);assert(max(abs(zCheck-sys.solution)) <1e-12)
For the fixed curve, take a very fine fit: the 5,121-node fit with the row factor, which the next section also uses as its reference. Restricted to each coarser grid’s nodes, it is the same shape seen at different resolutions.
factors=fx.resolution.factors;% 1, 4, 16, 64, 256 points per original intervalrefFactor=1024;gridRef=refineGrid(grid0,refFactor);zRef=solveStacked(fidelityRows(gridRef,x),...s*rowFactor(gridRef)*rangeFactor(gridRef)*secondDiff(gridRef),y);assert(numel(gridRef) ==fx.resolution.referenceNodes)nNodes=zeros(5,1);nRows=nNodes;withoutFactor=nNodes;withFactor=nNodes;fork=1:5g=refineGrid(grid0,factors(k));zShape=zRef(1:refFactor/factors(k):end);% same curve, sampled at gassert(max(abs(gridRef(1:refFactor/factors(k):end) -g)) <1e-12)rows=s*rangeFactor(g) *secondDiff(g) *zShape;% smoothness rows, no row factornNodes(k) =numel(g);nRows(k) =numel(g) -2;withoutFactor(k) =sum(rows.^2);withFactor(k) =rowFactor(g)^2*withoutFactor(k);endshapeTable=table(nNodes,nRows,withoutFactor,withFactor,...'VariableNames', {'nodes','N_s','SSE without row factor','SSE with row factor'});disp(shapeTable)
Without the row factor, the smoothness sum of the unchanged curve grows from about \(0.09\) on 6 nodes to about \(43\) on 1,281 nodes; from 21 nodes on, each fourfold refinement multiplies it by about four. With the factor, the same sums stay between \(0.168\) and \(0.171\) from 21 nodes on. The 6-node value, \(0.114\), is lower: four second differences over wide intervals smear out the curve’s bending.
The resolution study
The fixture repeats the full fit on grids of 6, 21, 81, 321, and 1,281 nodes, each made by refining every interval of the original grid. Each grid is solved twice with \(s=0.01\): once with the row factor, and once with it removed from the multiplier. Both versions keep the range factor. The reference is the 5,121-node fit with the row factor. “Max. dev.” is the largest difference from the reference at the nodes of each grid.
Nodes
With row factor: fid. SSE
smooth. SSE
max. dev.
Without row factor: fid. SSE
smooth. SSE
max. dev.
6
0.271358
0.159690
0.094850
0.227757
0.166802
0.136157
21
0.249744
0.167736
0.012627
0.501818
0.095076
0.226449
81
0.245067
0.168214
0.003248
0.647191
0.036544
0.367705
321
0.242977
0.168477
0.000782
0.702641
0.012728
0.443349
1281
0.242395
0.168553
0.000161
0.721934
0.003735
0.473571
The next cell recomputes every entry of that table with the page’s own helpers and checks it against the fixture. It keeps the fitted curves for plotting.
fits=cell(5,2);grids=cell(5,1);study=zeros(5,6);% [fid SSE, smooth SSE, max dev] with, then withoutfork=1:5g=refineGrid(grid0,factors(k));grids{k} =g;Af=fidelityRows(g,x);D=secondDiff(g);target=zRef(1:refFactor/factors(k):end);forj=1:2multiplier=s*rangeFactor(g);ifj==1,multiplier=multiplier*rowFactor(g);endL=multiplier*D;z=solveStacked(Af,L,y);fits{k,j} =z;study(k,3*j-2:3*j) = [sum((Af*z-y).^2),sum((L*z).^2),max(abs(z-target))];endendassert(max(abs(study- [fx.resolution.normalized,fx.resolution.withoutRowFactor]), [],'all') <1e-12)dev=study(:,3);fprintf('deviation ratio per fourfold refinement (with row factor): %s\n',mat2str(dev(1:end-1)./dev(2:end),3))fprintf('least-squares straight-line SSE: %.12f\n',fx.resolution.straightLineSSE)
deviation ratio per fourfold refinement (with row factor): [7.51;3.89;4.15;4.87]
least-squares straight-line SSE: 0.729530685921
Fitted curves on 6, 21, and 321 nodes with s = 0.01. Left: with the row factor, the curves close in on the 5,121-node reference. Right: without it, each refinement makes the curve stiffer, and it approaches the least-squares straight line.
figure;n=fx.resolution.nodes;semilogx(n,study(:,1),'-o','Color',blue,'LineWidth',1.5);holdon;gridon;semilogx(n,study(:,2),'-o','Color',orange,'LineWidth',1.5);semilogx(n,study(:,4),'--s','Color',blue,'LineWidth',1.5);semilogx(n,study(:,5),'--s','Color',orange,'LineWidth',1.5);yline(fx.resolution.straightLineSSE,':','Color',gray,'LineWidth',2);xlabel('grid nodes');ylabel('sum of squared residuals');title('Residual sums under grid refinement, s = 0.01');legend('fidelity, with row factor','smoothness, with row factor',...'fidelity, without','smoothness, without','straight-line SSE','Location','west');
Fidelity and smoothness sums of squares against the number of grid nodes. With the row factor (solid) both settle. Without it (dashed) the smoothness sum falls toward zero and the fidelity sum climbs toward the straight-line value.
With the row factor, the fits converge. The fidelity sum settles near \(0.242\) and the smoothness sum near \(0.169\). The deviation from the reference falls by a factor of between about \(3.9\) and \(7.5\) with each fourfold refinement. The fits are not identical across resolutions: the 6-node table still differs from the reference by \(0.094850\). That remaining difference is discretization error. A coarse grid can only represent piecewise-linear curves with a few kinks, and its second differences are only approximations of the curvature. Note that the reference is itself a fine-grid fit, so these deviations measure how fast the fits agree with each other, not the error against an exact continuous solution.
Without the row factor, refinement changes the answer systematically. The fidelity sum climbs from \(0.227757\) toward the least-squares straight-line value \(0.729530685921\), and the smoothness sum falls toward zero. The curve flattens into the least-squares line, because the line is the only shape with zero curvature. Nothing about the data or about \(s\) changed; only the row count did.
The drift has a simple form. Without the row factor the multiplier is \(s\,(g_N-g_1)^2\), which equals the normalized multiplier for a smoothness of \(s\sqrt{N_s/N_f}\). On the 1,281-node grid, \(N_s=1279\), so dropping the factor quietly turns \(s=0.01\) into about \(0.16\).
The range factor and the units of \(x\)
The multiplier’s last factor, \((g_N-g_1)^2\), makes \(s\) independent of the units of \(x\). Scaling the smoothness rows in Foundations 2 showed why: multiplying the grid by a constant \(k\) divides every second difference by \(k^2\) and multiplies the range factor by \(k^2\), so \(L\) is unchanged. The fidelity weights do not change either, because they depend only on where each sample sits within its interval.
This section looks at the other side: what the fit does when the range factor is left out. The smoothness rows are then divided by \(k^2\). For \(k=1000\) (kilometres to metres, say) the penalty all but disappears; for \(k=1/1000\) each smoothness row is weighted a million times more heavily than at \(k=1\). The next cell solves the fixture in three unit systems, with and without the range factor.
scales= [1e-3,1,1e3];zWith=zeros(6,3);zWithout=zeros(6,3);fidSSEWithout=zeros(1,3);forj=1:3xk=scales(j) *x;gk=scales(j) *grid0;Afk=fidelityRows(gk,xk);Lk=s*rowFactor(gk) *rangeFactor(gk) *secondDiff(gk);% regularizeNd styleLkNoRange=s*rowFactor(gk) *secondDiff(gk);% no range factorzWith(:,j) =solveStacked(Afk,Lk,y);zWithout(:,j) =solveStacked(Afk,LkNoRange,y);fidSSEWithout(j) =sum((Afk*zWithout(:,j) -y).^2);assert(full(max(abs(Afk-sys.fidelity), [],'all')) <1e-12)enddisp(array2table([grid0,zWith(:,2),zWithout],'VariableNames',... {'node (k = 1)','with range, any k','no range, k = 1e-3','no range, k = 1','no range, k = 1e3'}))fprintf('with range factor: max |z change| = %.1e\n',max(abs(zWith-sys.solution), [],'all'))fprintf('no range factor: fidelity SSE for k = 1e-3, 1, 1e3: %s (straight line %.6f)\n',...mat2str(fidSSEWithout,6),fx.resolution.straightLineSSE)assert(max(abs(zWith-sys.solution), [],'all') <1e-12)
node (k = 1) with range, any k no range, k = 1e-3 no range, k = 1 no range, k = 1e3
____________ _________________ __________________ _______________ _________________
0 0.95078 1.2625 0.78626 0.78462
1 1.2046 1.0401 1.398 1.4
2 0.65355 0.81776 0.15539 0.15
2.5 0.88104 0.70657 1.0283 1.0298
3 0.9258 0.59538 1.4497 1.4553
4 -0.047683 0.373 -0.47144 -0.47592
with range factor: max |z change| = 4.4e-16
no range factor: fidelity SSE for k = 1e-3, 1, 1e3: [0.729531 3.05225e-05 2.79953e-29] (straight line 0.729531)
figure;holdon;gridon;plot(grid0,zWith(:,2),'-','Color',gray,'LineWidth',4,'DisplayName','with range factor, any units');unitStyles= {'--s','--o','--^'};forj=1:3plot(grid0,zWithout(:,j),unitStyles{j},'LineWidth',1.2,...'DisplayName',sprintf('no range factor, k = %g',scales(j)));endplot(x,y,'x','Color',red,'MarkerSize',12,'LineWidth',2,'DisplayName','samples');xlabel('x (original units)');ylabel('y');title('Changing the units of x, s = 0.01');legend('Location','southwest');
The same five samples solved with x measured in three different units, plotted against x in the original units. With the range factor the three tables are identical, so one solid curve is drawn for all of them. Without it, the fit depends on the units, from the straight line (k = 1/1000) to a curve through the samples (k = 1000); the k = 1 and k = 1000 curves nearly coincide, differing by less than 0.006 at every node.
With the range factor, the regularizeNd-style table is the same in all three unit systems, up to floating-point rounding. Without it, the answer depends on the units of \(x\):
with \(k=1/1000\) the penalty dominates, and the fit is the least-squares straight line (its fidelity sum is \(0.729531\), the straight-line value);
with \(k=1\) the missing factor \((g_N-g_1)^2=16\) already makes the penalty much weaker than regularizeNd’s: the fidelity sum falls to about \(3\times10^{-5}\) and the curve nearly passes through the samples;
with \(k=1000\) the penalty is so weak that the fitted values match the samples to rounding error.
Connection to regularizeNd
regularizeNdMatrices builds exactly these two factors for every axis before it assembles that axis’s smoothness block. At upstream revision ef77fd0 the relevant lines are:
smoothnessScale=sqrt(nScatteredPoints/nSmoothnessEquations(iDimension));axisScale= (xGridMax(iDimension) -xGridMin(iDimension)).^2;% ... the block is then built with the product% smoothness(iDimension)*smoothnessScale*axisScale*secondDerivativeWeights(...)
nScatteredPoints is \(N_f\), the number of samples.
nSmoothnessEquations(iDimension) is \(N_s\) for that axis.
xGridMax and xGridMin are the grid’s extent along the axis.
That product is the multiplier \(m\) used on this page. Its two factors are why one smoothness value carries over between a coarse and a fine grid, and between axis units. A static call such as the following would give the fixture’s 6-node solution; the fixture reproduces it, and was cross-checked against the package to within \(8.88\times10^{-16}\):
With two or more inputs, each axis gets its own row count and its own range, so each block is normalized separately. See Scaling embedded in each regularization block in the deep dive for the n-D form, and Part 2: 1D Smoothing and Parameter Tuning for practical tuning of smoothness. Part 2’s advice to validate a candidate value on a second grid density fits the convergence shown above: with both factors in place, changing the grid should change the fit only by discretization error.
How this differs from the original
Convergence, not identity. The original states that a given smoothness constant should give the same result, and the same residual sums, whatever the number of output points. It attributes the small mismatch between its coarse and fine curves to quantization. The fixture makes this precise: with the row factor the fits converge as the grid is refined, and the sums settle (fidelity \(0.271358 \to 0.242395\), smoothness \(0.159690 \to 0.168553\)), but no two resolutions give identical answers.
Measuring the drift. Part 2 of the original series already predicts what happens without the square-root factor (Goldstein 2013a): the output tends toward a straight line as more points are computed, as if the smoothness constant had been raised. This page measures that drift on five grid resolutions and computes the effective smoothness it amounts to.
The range factor. The original scale is \(K\sqrt{N_f/N_d}\), with no \((g_N-g_1)^2\) term. As the units demonstration shows, without that term the fit depends on the units of \(x\). regularizeNd includes it, so its smoothness value means something different from the original’s \(K\), and the two cannot be swapped numerically.
Different example. The original plots a 10-point and a 10,001-point solution of its own example and mentions a 21-point case. This page uses the series’ five-sample fixture, five grid resolutions, and a 5,121-node reference, and adds the exact residual balance and the units comparison.
Terminology. The original calls one-input, one-output data “2D data”; this page follows regularizeNd and calls it a 1D input.
Next
With the row factor and the range factor in place, the five-sample example is complete: one smoothness value gives a stable fit whatever grid or units you choose. The next page turns the stacked equations into code, and shows why an efficient implementation never forms an explicit inverse and stores only what the sparse structure needs.