Skip to main content
v2026.11,986 entries · CC-BY 4.0

Linear Regression in MATLAB: fitlm and polyfit Step by Step

Fit a regression line with polyfit or a full linear model with fitlm, read the coefficient table and R-squared, and avoid the extra-column-of-ones error.

Written and maintained by CASRAI Editorial Board

Published · Last updated

On this page

Linear regression in MATLAB is done with fitlm when you need coefficient standard errors, p-values and diagnostics, or with polyfit(x,y,1) when you only need the slope and intercept of a regression line. This guide shows both, the exact syntax from the MathWorks documentation, how to read the output, and the mistakes that most often produce a wrong model. It is written for researchers fitting a straight line or a multiple linear model to measured data.

What linear regression in MATLAB is used for in research

Linear regression estimates how a response variable changes with one or more predictors. MathWorks describes simple linear regression as the relationship between a single predictor variable and a response variable; multiple regression extends this to several predictors. In MATLAB, three questions decide which function to use:

You need Use Source
Slope and intercept of one straight line, then evaluate it on new x values polyfit(x,y,1) with polyval MathWorks polyfit and linear regression pages
Coefficient estimates with standard errors, t statistics, p-values, R-squared, residuals, prediction and confidence intervals fitlm, which returns a LinearModel object MathWorks fitlm and LinearModel pages
Several predictors, interactions, squared terms or categorical predictors fitlm with a modelspec or formula and the CategoricalVars option MathWorks fitlm page

For fitting curves, polynomials of higher degree or custom models, see the CASRAI guides on fit in MATLAB and polyval in MATLAB, which this page does not repeat.

Install or access

fitlm and the LinearModel class require Statistics and Machine Learning Toolbox, according to the MathWorks documentation. polyfit and polyval are documented in the core MATLAB reference (MATLAB > Mathematics > Elementary Math > Polynomials). Get MATLAB and toolboxes only from mathworks.com or through your institution’s licence administrator.

Step-by-step: fit a regression line with polyfit

This example follows the MathWorks “Linear Regression” documentation page and uses its data.

  1. Put the data in column vectors and look at it first:
    x = [0:0.5:5]';
    y = [2.73 2.50 3.79 3.98 4.21 7.18 6.95 9.63 12.39 14.10 19.93]';
    scatter(x,y)
  2. Fit a first-degree polynomial, which is a linear fit, and keep the error structure:
    [pLinear,SLinear] = polyfit(x,y,1)

    The documentation output for these data is 3.1316 0.1155: pLinear(1) is the coefficient of x (the slope) and pLinear(2) is the constant term (the intercept). The fitted line is therefore about 3.1316x + 0.1155.

  3. Evaluate the line on a fine grid with polyval:
    xQuery = [0:0.05:7]';
    yLinear = polyval(pLinear,xQuery);
  4. Draw the regression line over the data:
    scatter(x,y)
    hold on
    plot(xQuery,yLinear,"-")
    hold off
  5. Read the goodness of fit from the error structure:
    linearR2 = SLinear.rsquared

    For this example the documentation reports 0.8715, and notes that a value close to 1 indicates a good fit.

Step-by-step: fit a linear model with fitlm

With a matrix of predictors

Syntax from the fitlm reference page: mdl = fitlm(X,y), where X is an n-by-p matrix of predictors and y is an n-by-1 numeric response. Do not include a column of ones in X; the constant term is included by default. The documentation example uses the carsmall data set:

load carsmall
X = [Weight,Horsepower,Acceleration];
mdl = fitlm(X,MPG)
mdl.Coefficients
mdl.Rsquared
plot(mdl)

With a table and a formula

With a table input, fitlm(tbl) treats the last variable as the response by default; fitlm(tbl,ResponseVarName) names it explicitly. A formula states the model directly:

tbl = table(Weight,Acceleration,MPG,'VariableNames',{'Weight','Acceleration','MPG'});
lm = fitlm(tbl,'MPG~Weight+Acceleration');

Choosing the model terms

The modelspec argument defaults to 'linear' (intercept plus one term per predictor). The other documented values are 'constant', 'interactions', 'purequadratic', 'quadratic', "poly_ijk", a terms matrix, or a formula such as 'y ~ x1 + x2^2 + x1:x2'. Name-value options documented on the same page include CategoricalVars, Exclude, Intercept, PredictorVars, ResponseVar, RobustOpts, VarNames and Weights.

Regression line matlab: plotting the line and the model

For a single predictor, the regression line is drawn by evaluating the fitted polynomial with polyval and plotting the result over a scatter of the data, as in step 4 above. For a fitlm model, plot(mdl) draws the added variable plot for the whole model excluding the constant term, as stated on the fitlm page. The LinearModel class also provides the methods plotResiduals and plotSlice.

Output and how to read it

Output What the MathWorks documentation says
mdl.Coefficients A table with columns Estimate, SE, tStat and pValue. tStat is Estimate divided by SE; pValue is two-sided.
mdl.Rsquared.Ordinary, mdl.Rsquared.Adjusted The Rsquared property is a structure with ordinary and adjusted values. The fitlm page example reports 0.752 for the carsmall model.
mdl.RMSE, mdl.MSE RMSE is the square root of MSE; MSE is SSE divided by the error degrees of freedom (DFE).
mdl.Residuals A table with Raw, Pearson, Standardized and Studentized residuals.
SLinear.rsquared (from polyfit) R-squared of the polynomial fit. The linear regression page says a value close to 1 indicates a good fit.

The LinearModel page also lists the methods predict, anova (for example anova(mdl,'summary')), coefCI, plotResiduals, plotSlice and plot. Check the LinearModel reference page for their exact arguments before use.

Practical reading order: look at the plot first, then the sign and size of each Estimate relative to its SE, then the pValue, then adjusted R-squared when comparing models with different numbers of predictors, since adjusted R-squared penalises model complexity (the linear regression page uses it for exactly that purpose). A high R-squared alone does not show the model form is right. For non-linear smoothing see LOESS regression, for another regression method see partial least squares regression, and for a polynomial extension see cubic regression.

Troubleshooting

  • The intercept appears twice or the model looks wrong with a matrix input. fitlm(X,y) adds the constant term itself, so remove any column of ones from X.
  • Slope and intercept are swapped. polyfit(x,y,1) returns the coefficient of x first and the constant term second.
  • The response is the wrong variable. With a table, the last variable is the response unless you pass ResponseVarName or a formula.
  • Undefined function fitlm. The function belongs to Statistics and Machine Learning Toolbox; confirm the toolbox is installed and licensed.
  • You need a model with no intercept. The Intercept name-value argument of fitlm controls the constant term.

Free alternatives

Tool Equivalent of the MATLAB call Difference to note (from the tool’s own documentation)
R lm(formula, data, ...) The R help page describes lm as used to fit linear models, with the model given as a symbolic formula and the variables taken from an optional data frame.
Python, statsmodels OLS, or OLS.from_formula The statsmodels documentation states that an intercept is not included by default and must be added with add_constant, unless you use formulas. This is the opposite default to fitlm(X,y).

Frequently asked questions

How do I do linear regression on MATLAB without a toolbox?

Use polyfit(x,y,1) and polyval, which are documented in the core MATLAB reference. fitlm needs Statistics and Machine Learning Toolbox.

How do I get the MATLAB linear regression line equation?

Fit with p = polyfit(x,y,1). Then p(1) is the slope and p(2) the intercept, so the line is p(1)*x + p(2). The MathWorks example builds the label with "Linear: " + pLinear(1) + "x + " + pLinear(2).

How do I get R-squared and p-values?

With fitlm, use mdl.Rsquared and the pValue column of mdl.Coefficients. With polyfit, read SLinear.rsquared from the second output.

Should I include a column of ones in X?

Not for fitlm. The documentation says to omit it because the constant term is included by default.

Sources

Follow CASRAI

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

Ask CASRAI · free to try

Ask about Linear Regression in MATLAB: fitlm and polyfit Step by Step

2 free questions a day, no account.

An AI assistant for research: funder rules, compliance, methods and publishing. It links the sources behind its answers and labels answers that come from a web search.

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 open 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 →