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.
0 个评论
回答(1 个)
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 个评论
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 Center 和 File Exchange 中查找有关 Interpolation 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!