Effacer les filtres
Effacer les filtres

How to fit line of best fit to scatterplot in R2012a

1 vue (au cours des 30 derniers jours)
Bianca Elena Ivanof
Bianca Elena Ivanof le 18 Nov 2016
Commenté : Star Strider le 19 Nov 2016
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.

Réponses (1)

Star Strider
Star Strider le 18 Nov 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 commentaires
Bianca Elena Ivanof
Bianca Elena Ivanof le 19 Nov 2016
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 le 19 Nov 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

Connectez-vous pour commenter.

Catégories

En savoir plus sur Discrete Data Plots dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by