How to fit line of best fit to scatterplot in R2012a

1 次查看(过去 30 天)
Hello,
Suppose I have 2 variables
curiosity = [4.916666667
3.916666667
3.666666667
5.083333333
4.666666667
3.75];
prediction = [19.58680175
-8.006943896
-2.934021031
32.79861546
78.37847569
41.84028306];
scatter(curiosity,prediction)
and I want to fit a standard regression line to it (without changing between polynomials - I'm only interested in the linear trend and not the cubic, quadratic or quartic one), how should I proceed? I've tried out solutions provided in a couple of answers to previous MATLAB questions but been unsuccessful so far.
Thank you very much in advance.

回答(1 个)

Star Strider
Star Strider 2016-11-18
Two possible ways:
Regression_Coefficients = polyfit(curiosity,prediction,1);
or:
Regression_Coefficients = [curiosity, ones(size(curiosity))]\prediction;
Regression_Coefficients =
21.8212e+000 -67.6145e+000
Regression_Coefficients =
21.8212e+000
-67.6145e+000
  2 个评论
Bianca Elena Ivanof
Bianca Elena Ivanof 2016-11-19
hello and thank you very much,
this gives me the regression coefficients but it doesn't fit a line to my scatterplot - or maybe I don't know how to do this still?
Star Strider
Star Strider 2016-11-19
My pleasure.
To plot the line for each (they both give the same result), the full code becomes:
curiosity = [4.916666667
3.916666667
3.666666667
5.083333333
4.666666667
3.75];
prediction = [19.58680175
-8.006943896
-2.934021031
32.79861546
78.37847569
41.84028306];
Regression_Coefficients_P = polyfit(curiosity,prediction,1)
Regression_Coefficients_M = [curiosity, ones(size(curiosity))]\prediction
x_plot = [min(curiosity); max(curiosity)]; % Only Need Two Points To Plot The Linear Fit
y_plot_P = polyval(Regression_Coefficients_P, x_plot) % Use ‘polyval’
y_plot_M = [x_plot [1; 1]] * Regression_Coefficients_M % Use Matrix Algebra
figure(1)
scatter(curiosity, prediction)
hold on
plot(x_plot, y_plot_P)
hold off
grid
figure(2)
scatter(curiosity, prediction)
hold on
plot(x_plot, y_plot_M)
hold off
grid

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Discrete Data Plots 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by