Polynomials, Interpolation and Curve Fitting
A polynomial is a vector of coefficients in descending powers: [1 -6 11 -6] is x³ − 6x² + 11x − 6.
Concept
A polynomial is a vector of coefficients in descending powers: [1 -6 11 -6] is x³ − 6x² + 11x − 6.
All roots (complex ones too) Coefficients from roots polyval(p, x) Evaluate (element-wise) conv(p, q), deconv Multiply / divide polynomials polyder, polyint Derivative / integral
interp1(x, y, xq, method) estimates values between known points: 'linear' (default), 'nearest', 'pchip' (shape-preserving), 'spline'. Outside the data range the result is NaN unless you pass 'extrap'. x must be monotonic. 2-D tables: interp2; scattered data: griddedInterpolant, scatteredInterpolant (MATLAB).
p = polyfit(x, y, n) finds the degree-n polynomial minimizing the sum of squared errors. Judge fits by residuals and R² = 1 − SSres/SStot. Non-polynomial models (exponential, power) can be linearized (e.g. log) or fitted by minimizing error with fminsearch (Module 24) or the Curve Fitting Toolbox (fit).
Why It Matters
Sensor calibration (ADC counts → volts), lookup tables in ECUs (engine maps, NTC thermistor curves), and empirical models from test data all rely on interpolation and fitting.
Syntax
r = roots([1 -3 2]); % [2; 1]
Tq = interp1(R, T, Rq, 'pchip');
c = polyfit(x, y, 1); yfit = polyval(c, x);Example
21.1 Roots, interpolation in a calibration table, least-squares fitting
p = [1 -6 11 -6]; % x^3 - 6x^2 + 11x - 6
fprintf('roots: %s\n', mat2str(sort(roots(p))', 6))
fprintf('polyval(p, 4) = %g\n', polyval(p, 4))
fprintf('conv([1 1], [1 -1]) = %s (x+1)(x-1) = x^2 - 1\n', mat2str(conv([1 1], [1 -1])))
fprintf('polyder(p) = %s, poly([1 2 3]) = %s\n', mat2str(polyder(p)), mat2str(poly([1 2 3])))
% linear interpolation in a calibration table (NTC thermistor: resistance -> temperature)
R = [32.6 10.0 3.6 1.5]; % kOhm
T = [0 25 50 75]; % degC
Rq = 5.0;
Tlin = interp1(fliplr(R), fliplr(T), Rq); % x must be monotonic: flip to increasing
fprintf('5.0 kOhm -> %.2f degC (linear interpolation)\n', Tlin)
t = 0:5; y = t .^ 2;
fprintf('interp1 at 2.5: linear %.3f, spline %.3f (exact 6.25)\n', interp1(t, y, 2.5), interp1(t, y, 2.5, 'spline'))
fprintf('outside the table: isnan = %d (NaN unless you pass ''extrap'')\n', isnan(interp1(t, y, 7)))
% least-squares curve fitting
x = 0:5;
yMeas = [1.1 2.9 5.2 7.1 8.8 11.2];
c = polyfit(x, yMeas, 1);
fprintf('linear fit: y = %.4f x + %.4f\n', c)
res = yMeas - polyval(c, x);
fprintf('R^2 = %.5f\n', 1 - sum(res .^ 2) / sum((yMeas - mean(yMeas)) .^ 2))
c2 =
…Expected Result
The roots of x³ − 6x² + 11x − 6 are 1, 2, 3; poly([1 2 3]) rebuilt the coefficients.
The thermistor table had to be flipped because interp1 needs increasing x values.
The spline reproduced the quadratic data exactly at 2.5 (6.25), linear interpolation overestimated it.
A value outside the table gave NaN.
The linear fit has R² close to 1.
roots: [1 2 3]
polyval(p, 4) = 6
conv([1 1], [1 -1]) = [1 0 -1] (x+1)(x-1) = x^2 - 1
polyder(p) = [3 -12 11], poly([1 2 3]) = [1 -6 11 -6]
5.0 kOhm -> 44.53 degC (linear interpolation)
interp1 at 2.5: linear 6.500, spline 6.250 (exact 6.25)
outside the table: isnan = 1 (NaN unless you pass 'extrap')
linear fit: y = 2.0029 x + 1.0429
R^2 = 0.99808
quadratic coefficients: [0.01071 1.949 1.079]Common Mistakes
Coefficient order confusion (MATLAB uses descending powers).
High-degree polyfit on noisy data (overfitting, oscillation); use low degrees or splines.
interp1 with unsorted or duplicate x values.
Extrapolating a fit far beyond the measured range.
Best Practices
Plot data and fit together; inspect residuals.
Center and scale x for high-degree fits ([p, S, mu] = polyfit(x, y, n)).
Use pchip for lookup tables that must not overshoot.
Interview Relevance
Medium: "how do you fit a line to data?", "interpolation vs regression?", "what is R²?", "why not use a high-degree polynomial?".
Practice Questions
Find the roots of x² + 2x + 5 and explain the complex result.
Interpolate an engine map lookup at 2750 rpm from a table at 1000-rpm steps.
Fit an exponential decay by fitting a line to log(y).
Compare linear, pchip and spline on a step-like dataset.
Quick Quiz
Q1. (Multiple choice) polyval([2 0 -1], 3) evaluates: A) 2 + 0·3 − 1·9 B) 2·3² − 1 C) 2·3 − 1 D) An error Answer: B — 17.
Q2. (Predict the output) interp1(0:5, (0:5).^2, 7) Answer: NaN — outside the table (verified).
Q3. (True/False) polyfit(x, y, 1) returns [slope intercept].
Answer: True. Q4. (Find the bug) interp1(R, T, 5) with R decreasing [32.6 10 3.6 1.5] fails.
Answer: x values must be monotonic increasing for interp1 in many versions; flip both vectors.
Coding Challenge
Fit a quadratic to the stopping distances d = [4.1 9.8 17.9 28.2 40.1] m at speeds v = [20 30 40 50 60] km/h and predict the distance at 70 km/h.
v = [20 30 40 50 60];
d = [4.1 9.8 17.9 28.2 40.1];
c = polyfit(v, d, 2);
fprintf('d = %.5f v^2 %+.4f v %+.3f\n', c)
fprintf('predicted at 70 km/h: %.1f m\n', polyval(c, 70))