calculate slope from linear fit data

264 ビュー (過去 30 日間)
Namira
Namira 2018 年 8 月 11 日
回答済み: Edward Vivanco 2019 年 11 月 10 日
I have this code to linear fit data
x = 1:10;
y1 = [1 5 7 8 9 15 16 12 18 20];
scatter(x,y1,'b','*')
P = polyfit(x,y1,1);
slope = P(1)
intercept = P(2)
yfit = P(1)*x+P(2); % P(1) is the slope and P(2) is the intercept
hold on;
plot(x,yfit,'r-.')
And the figure I got from code is attached here
The intercept from figure should be 2.2. But I get the value from code is 0.5.
I didn't understand why the values are different? The code seems correct to me. Any suggestion from anyone?

採用された回答

Ameer Hamza
Ameer Hamza 2018 年 8 月 11 日
編集済み: Ameer Hamza 2018 年 8 月 11 日
The intercept is indeed 0.5. Intercept is the value on y-axis when x=0. Whereas you 2.2 is the value when x=1.

その他の回答 (1 件)

Edward Vivanco
Edward Vivanco 2019 年 11 月 10 日
Error in 1st line: x = 1:10
Fix: x = 0:10

カテゴリ

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

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by