using a forloop to create vertical lines between regression line and scatter plot

4 ビュー (過去 30 日間)
Elisa Caruana
Elisa Caruana 2022 年 4 月 13 日
コメント済み: Elisa Caruana 2022 年 4 月 14 日
I have these X and Y variables
X=[1;2;3;4;5;6;7;8;9;10];
Y=[17;7;15;13;17;34;35;30;46;31];
I created a scatter plot using
scatter(X,Y,'+','r')
and this is the line of best fit (regression line)
Y =5.9333+3.3758*X;
i need to draw VERTICAL lines from the observed values given in the scatter plot to the fitted line, and measure their distance.
how can I do this using a forloop with MATLAB please? (was specifically asked to use a forloop)
  1 件のコメント
Elisa Caruana
Elisa Caruana 2022 年 4 月 14 日
I managed to do it, I had a mistake in labelling more than one thing as Y.
Thanks for the help!

サインインしてコメントする。

回答 (1 件)

Voss
Voss 2022 年 4 月 14 日
編集済み: Voss 2022 年 4 月 14 日
X=[1;2;3;4;5;6;7;8;9;10];
Y=[17;7;15;13;17;34;35;30;46;31];
% I created a scatter plot using
scatter(X,Y,'+','r')
% and this is the line of best fit (regression line)
% Y =5.9333+3.3758*X;
% calculate and plot the fitted line:
mb = polyfit(X,Y,1)
mb = 1×2
3.3758 5.9333
Y_fit = polyval(mb,X);
hold on
plot(X,Y_fit,'--b')
% construct and plot the vertical lines:
% (without for loop)
nans = NaN(numel(X),1);
xdata = [X X nans].';
ydata = [Y Y_fit nans].';
plot(xdata(:),ydata(:),'g');
% calculate the lengths of the vertical line segments:
len = abs(Y-Y_fit)
len = 10×1
7.6909 5.6848 1.0606 6.4364 5.8121 7.8121 5.4364 2.9394 9.6848 8.6909
% (put the scatter plot on top of the others)
set(gca(),'Children',flip(get(gca(),'Children')))
  2 件のコメント
Star Strider
Star Strider 2022 年 4 月 14 日
This is the complete solution to a homework problem.
Note that the regression equation is provided. It does not have to be calculated.
Voss
Voss 2022 年 4 月 14 日
I wanted to make sure the provided equation was correct.
I'll edit it to remove the loop, thus rendering the solution incomplete.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeScatter Plots についてさらに検索

製品


リリース

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by