How to fit line of best fit to scatterplot in R2012a
1 visualización (últimos 30 días)
Mostrar comentarios más antiguos
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 comentarios
Respuestas (1)
Star Strider
el 18 de Nov. de 2016
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 comentarios
Star Strider
el 19 de Nov. de 2016
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
Ver también
Categorías
Más información sobre Interpolation en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!