Thursday, 25 October 2012

Least Square Method(Least Square Regression) & Differentiation Matlab Code


%%%%%%%%%%%%%%% LEAST SQUARE REGRESSION %%%%%%%%%%%%%%%%%%%%%%%%%

clear all
x=[10 20 30 40 50 60 70];
y=[25 70 380 550 610 1220 830];
[m1,n1] = size(x);
[m2,n2] = size(y);
if n1 ~= n2
    error('Invalid data')
end
SumX = sum(x);
SumY = sum(y);
SumXY = sum(x.*y);
SumSqrX = sum(x.*x);
WholeSqrX = SumX * SumX;
a1 = (n1*SumXY - SumX*SumY)/(n1*SumSqrX - WholeSqrX);
a0 = (SumY/n1) - a1*(SumX/n1);
Yhati = zeros(n1,1);
Yhati = a0 + a1.*x;
Sr = sum((y-Yhati).*y-Yhati);
St = sum((y-(SumY/n1)).*(y-(SumY/n1)));
r=sqrt((St-Sr)/St);
r
plot(x,y,'-k',x,Yhati,'-g'), grid on
legend('Original Curve','Curve Fitted');

%%%%%%%%%%%%%%%%%%%% DIFFERENTIATION %%%%%%%%%%%%%%%%%%%%%%%%%


clear all
clc
X=[0 10 20 30 45 60 75];
Y=[10 20 15 16 19 22 35];

n=length(X);
m=length(Y);

if n~=m
error('not equal');
end
D=zeros(n,1);

for i=1:n
if i==1
D(i) = (Y(i+1) - Y(i))/(X(i+1) - X(i)); % Forward Formula
end
if i>1 && i<n
D(i) = (Y(i+1) - Y(i-1))/(X(i+1) - X(i-1)); % Central Formula
end
if i==n
D(i) = (Y(i) - Y(i-1))/(X(i) - X(i-1)); % Backward Formula
end
end
D

No comments:

Post a Comment