Linear regression with formulas

3 ビュー (過去 30 日間)
Olaf
Olaf 2019 年 9 月 23 日
コメント済み: Rena Berman 2019 年 10 月 28 日
Hey, I need to perform a linear regression with the formulas given
x and y with a line above are the average. And this gives the line:
I then need to make a function that takes x and y as arguments and returns the values for the coefficients â and ^b.
Here is my current code:
f = importdata("HadCRUT.4.6.0.0.monthly_ns_avg.txt");
data = f.data(:,1);
dates = f.textdata;
x = datenum(dates, "yyyy/mm");
y = data;
I then know that the function will look like this. After that I dont know how I should proceed, I've tried with a for loop without any success.
function [coeffA,coeffB] = lin_reg(x,y)
end
  1 件のコメント
Rena Berman
Rena Berman 2019 年 10 月 28 日
(Answers Dev) Restored edit

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

採用された回答

Sulaymon Eshkabilov
Sulaymon Eshkabilov 2019 年 9 月 24 日
Hi,
Here is the solution:
function [a, b] = linear_regression(x,y)
a = sum((x-mean(x)).*(y-mean(y)))./sum((x-mean(x)).^2);
b = mean(y)-a*mean(x);
end
Good luck
  1 件のコメント
Olaf
Olaf 2019 年 9 月 24 日
編集済み: Olaf 2019 年 9 月 24 日
Thanks, do you know how I then can plot y = ax + b inside another plot? Like this:
plox(x,y)
hold on
and then how can I plot the linear regression inside this?

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

その他の回答 (1 件)

Sulaymon Eshkabilov
Sulaymon Eshkabilov 2019 年 9 月 24 日
Hi,
Glad that I was of some help. Pl., click accept of my proposed answer. To plot your lin. reg model, use the following simple code:
x = 0:.1:13; % just an example
Y_model = a*x+b; plot(x, y, 'bo', x, Y_model, 'r-'), legend('Given Data Set', 'Linear regression fit model')
Good luck

カテゴリ

Help Center および File ExchangeSupport Vector Machine Regression についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by