Skip to main content
v2026.11,858 entries · CC-BY 4.0
LAC HealthMedical & Research SuppliesReagents, PPE & instruments — chain-of-custody documented.Fast, traceable sourcing built for regulated research environments, from bench consumables to instrumentation.Shop lac.us CodeCASRAIlac.us

Fit in MATLAB: polyfit, fit and fittype

How to fit data in MATLAB: polyfit in base MATLAB versus fit and fittype in Curve Fitting Toolbox, plus how to read goodness-of-fit output.

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)

  1. Put the data in two vectors of the same length, x and y.
  2. Fit a polynomial of degree n: coeffs = polyfit(x,y,n); The result lists coefficients from the highest power down.
  3. To get fit statistics too: [coeffs,fitStats] = polyfit(x,y,n);
  4. 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.
  5. 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)

  1. Call [fitobject,gof] = fit(x,y,fitType); The fitType argument selects the model.
  2. For a straight line use "poly1"; the library accepts polynomial names poly1 through poly9.
  3. For smoothing use "smoothingspline" (controlled by SmoothingParam), or "lowess" / "loess" (controlled by Span).
  4. For interpolation use one of linearinterp, cubicinterp, cubicspline, pchipinterp or nearestinterp.
  5. Ask for a third output, [fitobject,gof,output] = fit(...), to receive information about the fitting algorithm.
  6. Surfaces are fitted with fit([x,y],z,fitType).

3. Custom model with fittype

  1. 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"]).
  2. Fit it: [fitobject,gof] = fit(x,y,myfittype);
  3. Name-value options on fittype include coefficients, independent (default x), dependent (default y), problem and options.
  4. Linear terms can be given as a cell array, for example fittype({'x','sin(x)','1'}).
  5. For finer control, fit also accepts a fitoptions object or Name=Value arguments.

Common shapes: polynomial, exponential, logarithmic, loess

  • Polynomial fit: polyfit(x,y,n) in base MATLAB, or fit(x,y,"poly2") with the toolbox.
  • Logarithmic fit: define it with fittype, as in the a*log(x+b) example above, then call fit.
  • Exponential fit: define the expression you want, such as a*exp(b*x), with fittype and pass it to fit. For the least-squares logic behind exponential models see exponential regression.
  • Loess fit: fit(x,y,"loess"), with Span as 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:

Follow CASRAI

Research-administration guidance, standards updates and independent tool reviews.

Ask CASRAI · free to try

Ask about Fit in MATLAB: polyfit, fit and fittype

Ask your first 2 questions free below. Subscribers get 150 a day for $29 a month.

An AI assistant specialized in research administration. It cites the sources behind every answer, labels web answers and says when it can't answer.

Answers draw on CASRAI's guides and dictionary plus the federal and funder documents we index: Federal Register, Grants.gov, Regulations.gov and UKRI.

Works on this site and inside Claude, Cursor and the AI tools you already use.

Everything CASRAI publishes — this page, the dictionary, the guides and the news — stays free to read, with no account and no card.

Referenced across the research world

University of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logoUniversity of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logo
  • University of Cambridge logo
  • Columbia University logo
  • Crossref logo
  • University of Edinburgh logo
  • Harvard University logo
  • University of Oxford logo
  • Princeton University logo
  • Stanford School of Medicine logo
  • University College London logo
  • ORCID logo

View CASRAI adoption →