最小二乘法matlab程序(共5页).doc
精选优质文档-倾情为你奉上理解最小二乘法的基本原理,通过计算机解决相关问题;用matlab程序解决问题。1. 实验目的:(1)理解最小二乘法的基本原理,通过计算机解决相关问题;(2)用matlab解决问题。2. 实验内容: 给定一组实验数据(Xi,Yi)(i=1,2,n)编写一个通用程序,计算线性拟合和二次拟合(x,y)的值。3. 程序源代码及运行结果:(一)线性拟合x=1 2 3 4 5 6 7 8y=15.3 20.5 27.4 36.6 49.1 65.6 87.8 117.6x1=0;x12=0;y1=0;xy=0;n=8;for i=1:n x1=x1+x(i); x12=x12+x(i)2 y1=y1+y(i); xy=xy+x(i)*y(i);endx1y1x12xya0=(y1*x12-x1*xy)/(n*x12-x1*x1);a1=(n*xy-x1*y1)/(n*x12-x1*x1);a0a1yy =a0+a1*xplot(x,y,'o')plot(yy)运行结果:x = 1 2 3 4 5 6 7 8y = 15.3000 20.5000 27.4000 36.6000 49.1000 65.6000 87.8000 117.6000x12 = 1 5 14 30 55 91 140 204x1 = 36y1 = 419.9000x12 = 204xy = 2.4794e+003a0 = -10.7107a1 = 14.0440yy = Columns 1 through 7 3.3333 17.3774 31.4214 45.4655 59.5095 73.5536 87.5976 Column 8 101.6417>>(二)二次拟合xx=0;yy=0;x2=0;x3=0;x4=0;xy=0;y2=0;n=8;x1=1:8;y1=15.3 20.5 27.4 36.6 49.1 65.6 87.8 117.6;for i=1:n xx=xx+x1(i); x2=x2+x1(i)2; x3=x3+x1(i)3; x4=x4+x1(i)4; yy=yy+y1(i); xy=xy+x1(i)*y1(i); y2=y2+x1(i)*x1(i)*y1(i);endxxx2x3x4yyxyy2A=n xx x2;xx x2 x3;x2 x3 x4;B=yy;xy;y2;C=AB;C运行结果:xx =36x2 = 204x3 = 1296x4 = 8772yy = 419.9000xy = 2.4794e+003y2 = 1.6347e+004C = 18.8518 -3.6935 1.9708>>(三)线性拟合和二次拟合:function ZXE(x,y,m)S=zeros(1,2*m+1);T=zeros(m+1,1);for k=1:2*m+1 S(k)=sum(x.(k-1);endfor k=1:m+1T(k)=sum(x.(k-1).*y);endA=zeros(m+1,m+1);a=zeros(m+1,1);for i=1:m+1 for j=1:m+1 A(i,j)=S(i+j-1); endenda=AT;for k=1:m+1 fprintf('a%d=%fn',k,a(k);end运行结果:>> ZXE(x,y,1);a1=-10.a2=14.>> ZXE(x,y,2);a1=18.a2=-3.a3=1.>>图像:专心-专注-专业