필터 지우기
필터 지우기

How to fit line of best fit to scatterplot in R2012a

조회 수: 1 (최근 30일)
Bianca Elena Ivanof
Bianca Elena Ivanof 2016년 11월 18일
댓글: Star Strider 2016년 11월 19일
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