Curve Fitting
Curve fitting finds the parameters of a model that best describe measured data. You've already met the two basic tools: polyfit for polynomials in Polynomials, and fminsearch for a quick exponential fit in Roots & Minimization. This lesson builds a complete toolkit: any model that is linear in its parameters solved with backslash, goodness-of-fit numbers, numerical pitfalls of polyfit, nonlinear models, confidence intervals, and what the Curve Fitting Toolbox's fit function adds.
| Model type | Example | Tool |
|---|---|---|
| Polynomial | a + b·x + c·x² | polyfit, polyval |
| Linear in the parameters | a + b·sin(t) + c·cos(t), a + b·x₁ + c·x₂ | design matrix + \ |
| Linearisable | a·e^(bx) → log y = log a + b·x | polyfit on transformed data |
| Nonlinear | K / (1 + e^(−r(t − t₀))) | fminsearch on the sum of squared errors |
| Toolbox | anything, with statistics | fit (Curve Fitting Toolbox), lsqcurvefit, nlinfit |
"Best" almost always means least squares: minimise the sum of squared residuals, Σ (yᵢ − model(xᵢ))².
Linear least squares with backslash
A model is linear in the parameters when it's a weighted sum of known functions, even if those functions are curved. Put each function, evaluated at the data, in a column of a design matrix A; then A \ y returns the weights. Here a daily temperature cycle is fitted with a constant plus a 24-hour sine and cosine:
hour = (0:3:21)';
temp = [11.2; 10.1; 12.8; 17.9; 21.6; 21.0; 17.4; 13.6];
w = 2*pi / 24;
A = [ones(size(hour)) sin(w*hour) cos(w*hour)];
c = A \ temp;
fprintf('temp = %.3f %+.3f sin(wt) %+.3f cos(wt)\n', c);
amplitude = hypot(c(2), c(3));
peakHour = mod(atan2(c(2), c(3)) / w, 24);
fprintf('mean %.2f C, swing +/- %.2f C, warmest at %.1f h\n', c(1), amplitude, peakHour);temp = 15.700 -2.317 sin(wt) -5.287 cos(wt)
mean 15.70 C, swing +/- 5.77 C, warmest at 13.6 h
The sine and cosine pair is the standard way to fit a wave with unknown phase: amplitude and peak time follow from the two coefficients. The same pattern fits multiple regression with several predictors, one column per variable:
area = [50 65 80 95 110 70 85]'; % m^2
rooms = [2 3 3 4 4 2 3]';
price = [151 190 228 262 300 196 238]'; % thousand
A = [ones(7, 1) area rooms];
b = A \ price;
fprintf('price = %.2f + %.3f*area + %.2f*rooms\n', b);
pred = A * b;
R2 = 1 - sum((price - pred).^2) / sum((price - mean(price)).^2);
fprintf('R^2 = %.4f, prediction for 100 m^2, 4 rooms: %.1f\n', R2, [1 100 4] * b);price = 25.79 + 2.352*area + 3.78*rooms
R^2 = 0.9988, prediction for 100 m^2, 4 rooms: 276.1
R² (the coefficient of determination) is the fraction of the variation in y that the model explains: 1 is a perfect fit, 0 is no better than predicting the mean. It always rises when you add terms, so judge models by their residuals and by how they predict new data too.
polyfit details: scaling and diagnostics
polyfit is a design-matrix fit with columns xⁿ, …, x, 1. With x-values like years (around 2000), those columns differ by factors of 10⁹ and the problem becomes badly conditioned: MATLAB warns that the polynomial is badly conditioned and Octave that the matrix is singular to machine precision. The third output mu = [mean; std] tells polyfit to centre and scale x first, and polyval must then receive mu as well. The second output S holds diagnostics such as S.normr (norm of the residuals) and S.df (degrees of freedom):
yr = 2000:2010;
val = [5.0 5.4 6.1 6.5 7.4 8.0 8.9 9.5 10.6 11.2 12.4];
fprintf('cond of raw design matrix: %.1e\n', cond([yr'.^3 yr'.^2 yr' ones(11, 1)]));
z = (yr - mean(yr)) / std(yr);
fprintf('cond of scaled design matrix: %.1f\n', cond([z'.^3 z'.^2 z' ones(11, 1)]));
[p, S, mu] = polyfit(yr, val, 3);
fprintf('mu = [%.1f; %.4f], residual norm %.4f, df = %d\n', mu, S.normr, S.df);
fprintf('forecast for 2011: %.2f\n', polyval(p, 2011, [], mu));cond of raw design matrix: 2.7e+18
cond of scaled design matrix: 5.8
mu = [2005.0; 3.3166], residual norm 0.3419, df = 7
forecast for 2011: 13.31
Keep the degree low. A cubic through 11 noisy points is already generous; extrapolating a polynomial beyond the data (the 2011 forecast) is risky, because polynomials shoot off to ±∞.
Linearising versus fitting directly
An exponential y = a·e^(bx) becomes a straight line after taking logs: log y = log a + b·x. That makes polyfit(x, log(y), 1) a one-line fit. It's handy, but it is not the same fit: on the log scale, small y-values get as much weight as large ones, so the answer differs slightly from the true least-squares fit:
t = 0:6;
y = [10.2 6.1 3.8 2.2 1.4 0.8 0.5];
q = polyfit(t, log(y), 1);
fprintf('log-linear fit: a = %.4f, b = %.4f\n', exp(q(2)), q(1));
model = @(p, t) p(1) * exp(p(2) * t);
sse = @(p) sum((model(p, t) - y).^2);
opts = optimset('TolX', 1e-10, 'TolFun', 1e-12, 'MaxIter', 1e4, 'MaxFunEvals', 1e4);
p = fminsearch(sse, [exp(q(2)) q(1)], opts); % start from the linearised answer
fprintf('least-squares: a = %.4f, b = %.4f\n', p);
fprintf('SSE: log-linear %.4f, least-squares %.4f\n', sse([exp(q(2)) q(1)]), sse(p));log-linear fit: a = 10.1980, b = -0.5039
least-squares: a = 10.1854, b = -0.5032
SSE: log-linear 0.0143, least-squares 0.0141
The linearised answer is an excellent starting point for the nonlinear fit, which is how it was used here.
Nonlinear models with fminsearch
When no transformation makes the model linear, minimise the sum of squared errors directly. A logistic growth curve has three parameters: the capacity K, the growth rate r and the midpoint t₀. Sensible starting values come from the data: K a bit above the largest value, t₀ where the data pass half of it:
t = 0:10;
y = [2.1 3.2 5.1 7.9 11.6 15.9 19.8 22.9 25.0 26.3 27.0];
logistic = @(p, t) p(1) ./ (1 + exp(-p(2) * (t - p(3))));
sse = @(p) sum((logistic(p, t) - y).^2);
opts = optimset('TolX', 1e-10, 'TolFun', 1e-12, 'MaxIter', 1e4, 'MaxFunEvals', 1e4);
[p, fval, exitflag] = fminsearch(sse, [max(y) 1 5], opts);
fprintf('K = %.3f, r = %.3f, t0 = %.3f (exitflag %d)\n', p, exitflag);
fprintf('RMS residual: %.3f\n', sqrt(fval / numel(t)));K = 28.251, r = 0.588, t0 = 4.573 (exitflag 1)
RMS residual: 0.132
tt = linspace(0, 10, 200);
plot(t, y, 'o', tt, logistic(p, tt), '-', 'LineWidth', 1.5)
legend('data', 'logistic fit', 'Location', 'northwest')
xlabel('Day'); ylabel('Culture size'); title('Logistic growth fit')Results of iterative fits agree between MATLAB and Octave only to the tolerance, which is why they're printed to three or four decimals. Always check exitflag, plot the fit, and try a second starting point; a nonlinear fit can stop in a local minimum.
Confidence intervals by hand
How precisely do the data determine the parameters? Near the optimum, the Jacobian J (derivatives of the model with respect to each parameter, one row per data point) gives an approximate covariance matrix s²·(JᵀJ)⁻¹, where s² is the residual variance. For the exponential fit above:
t = 0:6;
y = [10.2 6.1 3.8 2.2 1.4 0.8 0.5];
model = @(p, t) p(1) * exp(p(2) * t);
opts = optimset('TolX', 1e-10, 'TolFun', 1e-12, 'MaxIter', 1e4, 'MaxFunEvals', 1e4);
[p, sse] = fminsearch(@(p) sum((model(p, t) - y).^2), [10 -0.5], opts);
J = [exp(p(2) * t)', (p(1) * t .* exp(p(2) * t))']; % d/da and d/db
df = numel(t) - numel(p);
s2 = sse / df;
se = sqrt(diag(s2 * inv(J' * J)))';
tcrit = 2.5706; % t quantile, 97.5%, 5 df
fprintf('a = %.4f 95%% CI (%.4f, %.4f)\n', p(1), p(1) - tcrit*se(1), p(1) + tcrit*se(1));
fprintf('b = %.4f 95%% CI (%.4f, %.4f)\n', p(2), p(2) - tcrit*se(2), p(2) + tcrit*se(2));
R2 = 1 - sse / sum((y - mean(y)).^2);
fprintf('SSE %.4f, R^2 %.4f, RMSE %.4f\n', sse, R2, sqrt(s2));a = 10.1854 95% CI (10.0576, 10.3132)
b = -0.5032 95% CI (-0.5147, -0.4917)
SSE 0.0141, R^2 0.9998, RMSE 0.0532
The t quantile is typed in because tinv belongs to MATLAB's Statistics and Machine Learning Toolbox and Octave's statistics package.
The Curve Fitting Toolbox: fit
MATLAB's Curve Fitting Toolbox wraps all of this in one function. fit knows dozens of model names ('poly2', 'exp1', 'fourier1', 'gauss2', 'smoothingspline'…), takes custom formulas with fittype, picks starting points, and reports confidence bounds. It needs column vectors. Octave doesn't have fit; its optim package offers lsqcurvefit and leasqr instead.
t = (0:6)';
y = [10.2 6.1 3.8 2.2 1.4 0.8 0.5]';
[f, gof] = fit(t, y, 'exp1')MATLAB output (Curve Fitting Toolbox):
f =
General model Exp1:
f(x) = a*exp(b*x)
Coefficients (with 95% confidence bounds):
a = 10.19 (10.06, 10.31)
b = -0.5032 (-0.5147, -0.4917)
gof =
struct with fields:
sse: 0.0141
rsquare: 0.9998
dfe: 5
adjrsquare: 0.9998
rmse: 0.0532The fitted object can be called like a function (f(7.5)), plotted with the data (plot(f, t, y)), differentiated (differentiate(f, t)) and integrated. The runnable confidence-interval example above computes the same numbers with base functions.
Learn more: the statistics behind regression are in Linear Regression; Python's version of this lesson is SciPy curve fitting; and the solvers used here are explained in Optimization.
Test yourself
Which model can be fitted with a design matrix and backslash?
- y = a + b·sin(t) + c·cos(t)
- y = a·sin(b·t)
- y = K / (1 + e^(−r t))
- y = a·x^b with unknown b
Why call [p, S, mu] = polyfit(x, y, n) when x contains values like years?
- To get more coefficients
- Centring and scaling x avoids a badly conditioned problem; evaluate with polyval(p, x, [], mu)
- To force the fit through the origin
- It is required for degree 1
Fitting log(y) with a straight line to get y = a·e^(bx)…
- gives exactly the least-squares fit of y
- gives a slightly different fit, because errors are weighted on the log scale
- only works for b > 0
- requires the Curve Fitting Toolbox