Need help with this code - linear regression/least squares
4 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Tristen Smith
am 27 Sep. 2016
Bearbeitet: Massimo Zanetti
am 27 Sep. 2016
the question and problem statement is on the pdf attachment. Tried my best with writing a code for it but I havn't taken matlab in 2 years so I'm extremely fuzzy. Down below is my first function statement but it didn't get included in the main code for some reason.
function CP2SmithTristen sumx=0; sumy=0; x= 1:5 ; y= [4, 7.1, 10.1, 12.5, 14.5]; end
function [a0,a1]=linear_regression(x,y)
for i = 1:5
n=length(x);
sumx = sumx + x(i);
sumy = sumy + y(i);
end
n = length(x);
a1=(n*(sumx*sumy)-sumx*sumy)/((n*sumx^2)-sumx^2);
a0=ym-(a1*xm);
xm = sumx/n
ym = sumy/n
end
0 Kommentare
Akzeptierte Antwort
Massimo Zanetti
am 27 Sep. 2016
Bearbeitet: Massimo Zanetti
am 27 Sep. 2016
Hi Tristen. Here is the function for Ordinary Least Squares to linear regression
function [a0,a1]=linear_regression(x,y)
x=x(:);
y=y(:);
X=[x,ones(numel(x),1)];
a = (X'*X)\(X'*y);
a0=a(2);
a1=a(1);
end
So you can try it:
x= 1:5;
y= [4, 7.1, 10.1, 12.5, 14.5];
[a0,a1]=linear_regression(x,y);
plot(x,y,'r*'); %points
hold on;
plot(x,a0+a1*x,'b'); %line
0 Kommentare
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Regression finden Sie in Help Center und File Exchange
Produkte
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!