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.
- 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) - 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) andpLinear(2)is the constant term (the intercept). The fitted line is therefore about 3.1316x + 0.1155. - Evaluate the line on a fine grid with
polyval:xQuery = [0:0.05:7]'; yLinear = polyval(pLinear,xQuery); - Draw the regression line over the data:
scatter(x,y) hold on plot(xQuery,yLinear,"-") hold off - Read the goodness of fit from the error structure:
linearR2 = SLinear.rsquaredFor 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 fromX. - 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
ResponseVarNameor 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
Interceptname-value argument offitlmcontrols 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
- MathWorks, fitlm, read 2026-11-08.
- MathWorks, LinearModel, read 2026-11-08.
- MathWorks, polyfit, read 2026-11-08.
- MathWorks, Linear Regression, read 2026-11-08.
- R Core Team, lm: Fitting Linear Models, read 2026-11-08.
- statsmodels, OLS, read 2026-11-08.







