Linear regression line in MATLAB scatter plot

user31820 picture user31820 · Jun 26, 2012 · Viewed 32.1k times · Source

I am trying to get the residuals for the scatter plot of two variables. I could get the least squares linear regression line using lsline function of matlab. However, I want to get the residuals as well. How can I get this in matlab. For that I need to know the parameters a and b of the linear regression line

ax+b

Answer

mathematician1975 picture mathematician1975 · Jun 26, 2012

Use the function polyfit to obtain the regression parameters. You can then evaluate the fitted values and calculate your residuals accordingly.

Basically polyfit performs least-squares regression for a specified degree N which, in your case will be 1 for straight line regression. The regression parameters are returned by the function and you can use the other function polyval to get the fitted values from the regression parameters