Written and maintained by CASRAI Editorial Board
Last updated
Short answer: to fit a curve in MATLAB, use polyfit for a polynomial in base MATLAB, or fit (Curve Fitting Toolbox) for polynomial, exponential, logarithmic, smoothing-spline, lowess/loess and custom models. fittype defines the custom model that fit then estimates. This guide is for researchers and analysts who need to pick the right function, run it, and read the goodness-of-fit numbers correctly.
What fitting is used for in research
Fitting estimates the parameters of a model that describes how a response y depends on a predictor x: a calibration line, a growth or decay curve, a dose-response relationship, a smoothed trend. MATLAB offers two routes, and they differ in what they need and what they return.
| Function | Where it lives | Use it when | Returns |
|---|---|---|---|
polyfit |
Base MATLAB (no toolbox listed on its reference page) | You only need polynomial coefficients of degree n | Coefficient vector; optionally a fit-statistics structure and centering/scaling values |
fit |
Curve Fitting Toolbox | You need a library model (poly1 to poly9, splines, lowess, loess, interpolants), a custom model, confidence information or goodness-of-fit statistics |
A fit object, plus a gof structure and an output structure |
fittype |
Curve Fitting Toolbox | You want to define a custom model (an expression, an anonymous function, or linear terms) before fitting | A fittype object you pass to fit |
Related pages on this site: polyval in MATLAB covers evaluating the coefficients that polyfit returns, and MATLAB graphing covers plotting the data and fitted curve together.
Install or access
polyfit and polyval are part of MATLAB itself. fit and fittype belong to the Curve Fitting Toolbox, and fitting with constraint points additionally requires the Optimization Toolbox (the fit reference page states that you must have it installed to use constraint points). Obtain MATLAB and its toolboxes only from MathWorks (mathworks.com) or through your institution’s licence; see MATLAB licensing for how institutional access is usually arranged.
Step-by-step: fit in MATLAB
1. Polynomial fit with polyfit (base MATLAB)
- Put the data in two vectors of the same length,
xandy. - Fit a polynomial of degree n:
coeffs = polyfit(x,y,n);The result lists coefficients from the highest power down. - To get fit statistics too:
[coeffs,fitStats] = polyfit(x,y,n); - To centre and scale x before fitting:
[coeffs,fitStats,centerScale] = polyfit(x,y,n,Normalize=true);The reference page states that normalization centres x at zero and scales it to unit standard deviation. - Evaluate the fitted curve:
yfit = polyval(coeffs,x);If you normalized, pass the centre-and-scale output as the fourth input:yfit = polyval(coeffs,x,[],centerScale);
2. Library-model fit with fit (Curve Fitting Toolbox)
- Call
[fitobject,gof] = fit(x,y,fitType);ThefitTypeargument selects the model. - For a straight line use
"poly1"; the library accepts polynomial namespoly1throughpoly9. - For smoothing use
"smoothingspline"(controlled bySmoothingParam), or"lowess"/"loess"(controlled bySpan). - For interpolation use one of
linearinterp,cubicinterp,cubicspline,pchipinterpornearestinterp. - Ask for a third output,
[fitobject,gof,output] = fit(...), to receive information about the fitting algorithm. - Surfaces are fitted with
fit([x,y],z,fitType).
3. Custom model with fittype
- Define the model as text, an anonymous function, or a list of linear terms. The reference example is
myfittype = fittype("a*log(x+b)", dependent="y", independent="x", coefficients=["a" "b"]). - Fit it:
[fitobject,gof] = fit(x,y,myfittype); - Name-value options on
fittypeincludecoefficients,independent(defaultx),dependent(defaulty),problemandoptions. - Linear terms can be given as a cell array, for example
fittype({'x','sin(x)','1'}). - For finer control,
fitalso accepts afitoptionsobject or Name=Value arguments.
Common shapes: polynomial, exponential, logarithmic, loess
- Polynomial fit:
polyfit(x,y,n)in base MATLAB, orfit(x,y,"poly2")with the toolbox. - Logarithmic fit: define it with
fittype, as in thea*log(x+b)example above, then callfit. - Exponential fit: define the expression you want, such as
a*exp(b*x), withfittypeand pass it tofit. For the least-squares logic behind exponential models see exponential regression. - Loess fit:
fit(x,y,"loess"), withSpanas the smoothing control.
Output and how to read it
The second output of fit, gof, has five fields. Each answers a different question, so pick the comparator that matches your decision.
| Field | What it measures (per the MathWorks documentation) | How to use it |
|---|---|---|
sse |
Sum of squares due to error. A value closer to 0 means a smaller random error component. | Compare fits of the same data when the number of terms is equal. |
rsquare |
The square of the correlation between observed and predicted values, between 0 and 1. It can be negative for a model without a constant term. | Describe how much variation the model accounts for. See the coefficient of determination formula. |
dfe |
Degrees of freedom in the error. | Needed to interpret adjusted R-square and RMSE. |
adjrsquare |
R-square adjusted for residual degrees of freedom. It is described as the best indicator for comparing nested models, and is negative when added terms do not help. | Choose between polynomial degrees (for example poly2 versus poly3). |
rmse |
Root mean squared error, sqrt(SSE/dfe): an estimate of the standard deviation of the random error. | Report the typical size of the residual in the units of y. |
A high R-square alone does not show that the model form is right. Check residuals and read the assumptions in assumptions of simple regression before reporting a fit.
Troubleshooting
polyfit gives unstable coefficients at high degree
The reference page warns that an ill-conditioned fit can result from a high polynomial degree. Use Normalize=true and keep the centerScale output so that polyval can apply the same centring and scaling. Before MATLAB R2026b, requesting the third output enabled normalization automatically; the page now documents Normalize as an explicit name-value argument, so scripts written for older releases should be checked.
Fitted values are wrong after normalizing
Calling polyval(coeffs,x) without the centre-and-scale input evaluates the coefficients on unscaled x. Pass centerScale as the fourth input.
Error about constraint points
Constraint points need the Optimization Toolbox as well as the Curve Fitting Toolbox.
Negative R-square or adjusted R-square
Per the documentation, R-square can be negative when the model has no constant term, and adjusted R-square is negative when the added terms do not improve the fit. Both signal a model worse than a constant, not a software fault.
Free alternatives
| Tool | Function | Note |
|---|---|---|
| Python (NumPy / SciPy) | numpy.polyfit, scipy.optimize.curve_fit |
See curve fitting with SciPy for worked usage. |
| R | lm (linear models), nls (nonlinear least squares) |
See MATLAB vs R for how the two environments compare. |
| GNU Octave | polyfit |
Octave provides a function of this name for polynomial fitting, but check argument and output differences against its own manual before porting scripts. |
Frequently asked questions
What is the difference between polyfit and fit?
polyfit is a base-MATLAB function that returns polynomial coefficients. fit is a Curve Fitting Toolbox function that returns a fit object with goodness-of-fit statistics and supports many more model types.
What does fittype do?
It creates a model definition (a library name, an expression, an anonymous function or linear terms) that you pass to fit.
Can I fit an exponential or logarithmic curve?
Yes, by defining the expression with fittype and fitting it with fit; the logarithmic a*log(x+b) expression is the example in the MathWorks reference.
Which goodness-of-fit statistic should I report?
Report RMSE for the size of the error and adjusted R-square when comparing nested models. Use R-square to describe explained variation, and always inspect residuals.
Sources
MathWorks documentation, read 2026-11-07:







