Curve Fitting Basics

Curve Fittingbeginner~8 min

Fit polynomials and exponential models to experimental data and assess goodness-of-fit.

Step 1 — Linear fit with polyfit

polyfit(x, y, 1) fits a straight line (degree-1 polynomial) to the data. The returned coefficients [m, b] define y = m*x + b.

x = [1 2 3 4 5];
y = [2.1 3.9 6.2 7.8 10.1];
p = polyfit(x, y, 1);
printf('Slope: %.2f, Intercept: %.2f\n', p(1), p(2))
▶ Run in SimLab

Expected output: Slope near 2.0, Intercept near 0.1

Step 2 — Evaluate and plot the fit

polyval(p, x) evaluates the fitted polynomial at any x values. Plot both the original data points ('o') and the fitted line to judge the quality visually.

x = [1 2 3 4 5];
y = [2.1 3.9 6.2 7.8 10.1];
p = polyfit(x, y, 1);
x_fine = linspace(1, 5, 100);
y_fit = polyval(p, x_fine);
plot(x, y, 'o', x_fine, y_fit);
legend('Data', 'Linear fit');
title('Curve Fitting')
▶ Run in SimLab

Expected output: Scatter of data points with a fitted line through them

Step 3 — Higher-degree polynomial

Increase the degree to capture curvature. Degree 2 fits a parabola; watch out for overfitting with very high degrees.

x = linspace(0, 2*pi, 20);
y = sin(x) + 0.2*randn(1, 20);
p3 = polyfit(x, y, 3);
x_fine = linspace(0, 2*pi, 200);
plot(x, y, 'o', x_fine, polyval(p3, x_fine));
legend('Noisy data', 'Degree-3 fit');
title('Polynomial Curve Fitting')
▶ Run in SimLab

Expected output: Smooth cubic curve fitting the noisy sine data

Related Tutorials

Try SimLab — MATLAB®-compatible, free, in your browser

466 functions. Runs in your browser. No install.

Open SimLab

MATLAB® is a registered trademark of The MathWorks, Inc. SimLab is an independent project by Simulations4All and is not affiliated with, endorsed by, or sponsored by The MathWorks, Inc.

Stay Updated

Get notified about new simulations and tools. We send 1-2 emails per month.