0
0
MATLABdata~5 mins

Curve fitting (polyfit, fit) in MATLAB

Choose your learning style9 modes available
Introduction

Curve fitting helps you find a smooth line or curve that best matches your data points. It makes it easier to understand trends and predict values.

You have scattered data points and want to find a simple formula that describes them.
You want to predict future values based on existing data.
You want to smooth noisy measurements to see the overall pattern.
You want to compare how well different types of curves fit your data.
Syntax
MATLAB
p = polyfit(x, y, n)

% or using fit function
f = fit(x, y, 'polyN')

polyfit returns coefficients of a polynomial of degree n that fits data x, y.

fit returns a fit object that can be used to evaluate or plot the fitted curve.

Examples
Fits a straight line (degree 1 polynomial) to data points x and y.
MATLAB
p = polyfit(x, y, 1)
Fits a quadratic curve (degree 2 polynomial) to the data.
MATLAB
p = polyfit(x, y, 2)
Fits a cubic polynomial using the fit function.
MATLAB
f = fit(x, y, 'poly3')
Sample Program

This program fits a straight line and a quadratic curve to the sample data points. It prints the slope and intercept for the line, and the coefficients for the quadratic curve.

MATLAB
x = 1:5;
y = [2.2, 2.8, 3.6, 4.5, 5.1];

% Fit a line using polyfit
p = polyfit(x, y, 1);

% Display the coefficients
fprintf('Slope: %.2f, Intercept: %.2f\n', p(1), p(2));

% Use fit function for quadratic fit
f = fit(x', y', 'poly2');

% Display the fit object coefficients
coeffs = coeffvalues(f);
fprintf('Quadratic fit coefficients: a=%.2f, b=%.2f, c=%.2f\n', coeffs(1), coeffs(2), coeffs(3));
OutputSuccess
Important Notes

Always check the degree of the polynomial; higher degrees can fit data better but may cause overfitting.

The fit function requires column vectors, so transpose row vectors if needed.

You can use polyval to evaluate the polynomial at new points after using polyfit.

Summary

Curve fitting finds a simple curve that best matches your data points.

polyfit returns polynomial coefficients; fit returns a fit object.

Use the fit to predict or understand data trends easily.