You are on page 1of 5

Name – ajay kumar

Roll no – 144

AIM – 5: Write a program for weighted least


square fitting of given data (x, y)

CODE:

clf
clc
clear
x=[0 2 5 7]
y=[-1 5 12 20]
//Least Square Fitting
w=[1 1 1 1]
wx=[0 2 5 7]
wxx=[0 4 25 49]
wy=[-1 5 12 20]
wxy=[0 10 60 140]
disp("---------------------------------------------------")
mprintf(" x\ty w\t wx\t wxx\twy\twxy\n");
s=[x;y;w;wx;wxx;wy;wxy]
disp(s')
W=sum(w)
WX=sum(w.*x)
WX2=sum(w.*x.*x)
WY=sum(w.*y)
WXY=sum(w.*y.*x)
m=(WX*WY - WXY*W)/((WX^2)-(W*(WX2)))
c=(WY-m*WX)/W
Y=m*x+c
//Weighted Least Square Fitting
wl=[1 1 10 1]
wxl=[0 2 50 7]
wxxl=[0 4 250 49]
wyl=[-1 5 120 20]
wxyl=[0 10 600 140]
Wl=sum(wl)
WXl=sum(wl.*x)
WX2l=sum(wl.*x.*x)
WYl=sum(wl.*y)
WXYl=sum(wl.*x.*y)
ml=((WYl*WXl)-(WXYl*Wl))/((WXl^2)-
(Wl*(WX2l)))
cl=(WYl-ml*WXl)/Wl
Yl=ml*x+cl
disp("----------------------------------------------------")
disp("Least Square Fitting: Slope= "+string(m)+"
Intercept= "+string(c))
disp("----------------------------------------------------")
mprintf(" x\ty w\t wx\t wxx\twy\twxy\n");
s=[x;y;wl;wxl;wxxl;wyl;wxyl]
disp(s')
disp("---------------------------------------------------")
disp("Weighted Least Square Fitting: Slope=
"+string(ml)+" Intercept="+string(cl))
plot2d(x,y,-6)
plot2d(x,Y,2)
plot2d(x,Yl,5)
title("Weighted Least Square
LinearFitting","color",35,"edgecol",1,"fontsize",4
,"fontname",7)
xlabel("x","color",25,"fontsize",4,"fontname",7)
ylabel("y(x)","color",25,"fontsize",4,"fontname",
7)
L=legend('Actual Data Points','Least Square
Fitting','Weighted LeastSquare Fitting')
L.font_size=3
L.font_style=3
a=gca()
b=a.children.children
b.thickness=3
a.box="on"
a.x_location="origin"
a.y_location="origin"
a.data_bounds=[-0.2,-1.2;7,20]

output-

You might also like