How to make a linear regression coefficient algorithm
3 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
I wrote this code and I don't know how to use the formulae
function [alpha, beta] = linreg( x, y )
beta = cov( x, y ) / var( x ) ;
% ...
end

1 Kommentar
Rik
am 21 Mär. 2023
Only the definition for alpha is missing. What exactly is your question, and how exactly is this a Matlab question?
Antworten (3)
Sugandhi
am 21 Mär. 2023
Bearbeitet: Sugandhi
am 21 Mär. 2023
Hi Karthik,
I understand that you want to make a linear regression coefficient algorithm by using the above formula.
function [alpha, beta] = linreg( x, y )
beta = cov( x, y ) / var( x ) ;
xbar=mean(x);
ybar=mean(y);
alpha = ybar+beta*xbar;
end
According to the formula provided, xbar and ybar are mean of x and y data respectively. Alpha is calculated using xbar,ybar and beta. Beta is ratio of covariance of x,y and variance of x data.
For more understanding, kindly go through following links-
- mean- https://www.mathworks.com/help/matlab/ref/mean.html?searchHighlight=mean&s_tid=srchtitle_mean_1
- Covariance- https://www.mathworks.com/help/matlab/ref/cov.html?searchHighlight=cov&s_tid=srchtitle_cov_1
- Variance- https://www.mathworks.com/help/matlab/ref/var.html?searchHighlight=var&s_tid=srchtitle_var_1
0 Kommentare
KSSV
am 21 Mär. 2023
Bearbeitet: KSSV
am 21 Mär. 2023
x = 1:10 ;
y = rand(1,10) ;
[a,b] = linreg(x,y) ;
% Check
p = polyfit(x,y,1) ;
[a b ; p(2) p(1)]
function [alpha, beta] = linreg( x, y )
n = length(x) ; % get the length of x and y
xbar = mean(x) ; % mean of x
ybar = mean(y) ; % mean of y
Sxy = 1/(n-1)*sum((x-xbar).*(y-ybar)) ;
Sx2 = 1/(n-1)*sum((x-xbar).^2) ;
beta = Sxy/Sx2 ;
alpha = ybar-beta*xbar ;
end
0 Kommentare
John D'Errico
am 21 Mär. 2023
Bearbeitet: John D'Errico
am 21 Mär. 2023
Why do you want to write your own linear regression code? This is generally a bad idea. Never write code to do what a professional will have done better, and has already been written for you.
ab = polyfit(x,y,1);
Alph = ab(2);
Bet = ab(1);
0 Kommentare
Siehe auch
Kategorien
Mehr zu Linear Regression finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!