How to do linear regression?

How to do a regression line ?

1 个评论

Do you have access to Optimization Toolbox or to Curve Fitting Toolbox?

请先登录,再进行评论。

回答(2 个)

Star Strider
Star Strider 2018-8-22

1 个投票

To do a simple linear least-square fit, see the mldivide,\ (link) function.

5 个评论

Note that this solution only gives a correct answer, when the function passes through the origin of the coordinate system
y= m .* x + n ---> with n = 0
will give a correct answer. If n~=0 you get more bad results for m the more n is different from zero.
It gives a correct result if you include a column vector of ones with the independent variable to estimate the intercept:
B = [x(:) ones(size(x(:)))] \ y(:); % Estimate Parameters
yfit = [x(:) ones(size(x(:)))] * B; % Calculate Regression Line
figure
plot(x, y, 'pg')
hold on
plot(x, yfit, '-r')
hold off
grid
The polyfit (link) and polyval (link) options, with a polynomial order of 1, will also work.
Nice,
and learned something again ;-)
Thank you!
Actually, I got the idea for the column of ones from the documentation for the regress (link) function when I first began using it, many years ago. (I simply forgot to include polyfit and friends initially.)
I had to think about it for a few minutes. But after understanding what happens, i saw that this is a pretty nice approach.

请先登录,再进行评论。

类别

帮助中心File Exchange 中查找有关 Get Started with Curve Fitting Toolbox 的更多信息

标签

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by