实验二:曲线拟合目的与要求:了解最小二乘法的基本原理,用最小二乘法求拟合数据的多项式,做出离散函数),(iiyx和拟合函数的图形,掌握利用最小二乘法进行数据拟合的基本思想,熟悉寻找最佳方法拟合曲线的方法,通过计算机解决实验问题例题1已知观测数据x00.10.20.30.40.50.60.70.80.91y-0.4471.9783.286.167.087.347.669.569.489.311.2对实验一中的例题2进行曲线拟合x=0:0.1:1;y=[-0.4471.9783.286.167.087.347.669.569.489.311.2];plot(x,y,'k.','markersize',25)axis([01.3-216])p=polyfit(x,y,3);p1=polyfit(x,y,6);t=0:0.01:1.2;s=polyval(p,t);s1=polyval(p1,t);holdonplot(t,s,'k-','linewidth',2)plot(t,s,'k--','linewidth',2)grid;例题2已知观测数据x1345678910y1054211234求一代数多项式曲线,使其最好地拟合这组给定数据。(1)画出数据分布趋势图xi=[1345678910];yi=[1054211234];plot(xi,yi,'o')(2)建立数学模型y=a2x^2+a1x+a0建立超定方程组系数矩阵A=[ones(size(xi));xi;xi.^2]'A=111139141615251636174918641981110100(3)求超定方程组的最小二乘解a=A\yi'a=13.4597-3.60530.2676(4)求拟合曲线方程b=[0.2376-3.605313.4597]b=0.2376-3.605313.4597y=poly2str(b,'x')y=0.2376x^2-3.6053x+13.4597f2=polyval(flipud(a),xi);plot(xi,yi,'bo',xi,f2,'r-')(5)用方程y=ax^b拟合x=[ones(size(xi));log(xi)];aa=x'\log(yi)'aa=2.1257-0.6913yy=exp(2.1257)*xi.^(-0.6913);yy=exp(2.1257)*xi.^(-0.6913);plot(xi,yi,'bo',xi,yy,'r--',xi,f2,'b-')例题3已知观测数据x0.10.40.50.70.70.9y0.610.920.991.521.472.03用polyfit命令作拟合直线并计算偏差。fprintf('ix(i)y(i)y=c_1x+c_2偏差\n');fori=1:6x=[0.10.40.50.70.70.9];y=[0.610.920.991.521.472.03];c=polyfit(x,y,1);error=y(i)-(c(1)*x(i)+c(2));fprintf('%2d%2.1f%5.2f%10.4f%10.5f\n',i,x(i),y(i),c(1)*x(i)+c(2),error);endix(i)y(i)y=c_1x+c_2偏差10.10.610.46260.1473820.40.920.9920-0.0719830.50.991.1684-0.1784440.71.521.5214-0.0013550.71.471.5214-0.0513560.92.031.87430.15574任务:由化学实验得到某物质浓度与时间的关系如下:时间t12345678浓度y4.006.408.008.809.229.509.709.86时间t910111213141516浓度y10.0010.2010.3210.4210.5010.5510.5810.60求浓度与时间的二次拟合曲线。运行及结果显示:044466.0]2[,065962.1]1[,3875000.4]0[aaa