Need help with Least Squares fit problem! Not overly difficult I don't believe.

3 ビュー (過去 30 日間)
Hello, I am doing some homework for my computational methods class and need some help. We are covering linear regressions and least fit squares. So the problem I am doing is having me derive by hand the least fit squares for the equation y=a1x+e, meaning determine the slope that results from a straight line with a zero intercept. I did it by hand and got a slope of 0.61436, but was wondering how I would go about checking on matlab if this was correct?
The x and y data are as follows: X: 2 4 6 7 10 11 14 17 20 Y: 4 5 6 5 8 8 6 9 12 I understand basic plotting but am unsure of how to fit the line to it on here. Thanks!

採用された回答

Star Strider
Star Strider 2017 年 10 月 8 日
Use the MATLAB mldivide,\ (link) function to calculate the least-squares fit:
X = [2 4 6 7 10 11 14 17 20];
Y = [4 5 6 5 8 8 6 9 12];
a1_1 = X(:)\Y(:) % Using ‘mldivide,\’
You may want to check your calculations and derivation, since I get a different result from taking the first (partial) derivative of:
S = sum((Y - a1*X)^2)
with respect to ‘a1’, then setting it to zero and solving for ‘a1’:
a1_2 = sum(X.*Y)/sum(X.^2) % Using Computed Least Squares
My derivation result agrees with the mldivide result.
Plotting:
figure(1)
plot(X, Y, 'pg')
hold on
plot(X, a1_1*X, '-r')
hold off
grid
text(7, 11, sprintf('Y = %.3f\\cdotX', a1_1))
text(7, 13, sprintf('Y = %.3f\\cdotX', a1_2))
  2 件のコメント
Grant Piephoff
Grant Piephoff 2017 年 10 月 8 日
Thank you so much! I recalculated my numbers and got the same value as you.
Star Strider
Star Strider 2017 年 10 月 8 日
As always, my pleasure!
I decided to do the derivation as well (by hand, not using the Symbolic Math Toolbox) to be certain I could get the same result.

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

その他の回答 (1 件)

Kaushik Lakshminarasimhan
Kaushik Lakshminarasimhan 2017 年 10 月 8 日

カテゴリ

Help Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by