1、曲线拟合的最小二乘法1、%采用二次多项式拟合%a 的输出为多项式各项系数%b 为拟合曲线各点函数值%phi 为输出的曲线拟合函数x=0:5:55;y=0 1.27 2.16 2.86 3.44 3.87 4.15 4.37 4.51 4.58 4.02 4.64;a=polyfit(x,y,2)b=polyval(a,x)syms tphi=a(1)*t2+a(2)*t+a(3)运行结果: leastwaya =-0.0024 0.2037 0.2305b =Columns 1 through 50.2305 1.1894 2.0293 2.7502 3.3521Columns 6 throu
2、gh 103.8349 4.1987 4.4435 4.5693 4.5760Columns 11 through 124.4637 4.2324phi =2-0.00238051948051948162 t + 0.203690809190809258 t + 0.2304670329670317492、%采用三次多项式拟合x=0:5:55;y=0 1.27 2.16 2.86 3.44 3.87 4.15 4.37 4.51 4.58 4.02 4.64;a=polyfit(x,y,3)b=polyval(a,x)syms tphi=a(1)*t3+a(2)*t2+a(3)*t+a(4)运
3、行结果: leastwaya =0.0000 -0.0052 0.2634 0.0178b =Columns 1 through 50.0178 1.2087 2.1646 2.9113 3.4745Columns 6 through 103.8800 4.1536 4.3211 4.4082 4.4407Columns 11 through 124.4444 4.4450phi =3 20.0000343641543641541613 t - 0.00521556221556219567 t+ 0.263398527398526872 t + 0.01783882783883230383、%
4、delta 为拟合函数值与原函数值的误差clcclearx=0:5:55;y=0 1.27 2.16 2.86 3.44 3.87 4.15 4.37 4.51 4.58 4.02 4.64;a=polyfit(x,y,3);b=polyval(a,x);for j=1:12 delta=b(j)-y(j)endsyms tphi=a(1)*t3+a(2)*t2+a(3)*t+a(4)运行结果:delta =0.0178delta =-0.0613delta =0.0046delta =0.0513delta =0.0345delta =0.0100delta =0.0036delta =-0
5、.0489delta =-0.1018delta =-0.1393delta =0.4244delta =-0.1950phi =3 20.0000343641543641541613 t - 0.00521556221556219567 t+ 0.263398527398526872 t + 0.01783882783883230384、%采用四次多项式拟合与三次多项式拟合进行比较%输出其与原函数值的误差再与之前输出的三次与原函误差进行比较%delta4 为四次与原函的误差clcclearx=0:5:55;y=0 1.27 2.16 2.86 3.44 3.87 4.15 4.37 4.51
6、 4.58 4.02 4.64;a=polyfit(x,y,4);b=polyval(a,x)for j=1:12delta4=b(j)-y(j)endsyms tphi=a(1)*t4+a(2)*t3+a(3)*t2+a(4)*t+a(5)运行结果:b =Columns 1 through 50.0604 1.1739 2.1220 2.8945 3.4900Columns 6 through 103.9162 4.1898 4.3366 4.3914 4.3981Columns 11 through 124.4095 4.4876delta4 =0.0604delta4 =-0.0961d
7、elta4 =-0.0380delta4 =0.0345delta4 =0.0500delta4 =0.0462delta4 =0.0398delta4 =-0.0334delta4 =-0.1186delta4 =-0.1819delta4 =0.3895delta4 =-0.1524phi =-6 4 30.602564102564107288 10 t - 0.0000319178969178975504t2- 0.00293227466977464190 t +0.238069314944314520t+ 0.06044871794871947705、%分别采用二次、四次、六次、九次多
8、项式拟合并画出其曲线进行比较clcclearx=0:5:55;y=0 1.27 2.16 2.86 3.44 3.87 4.15 4.37 4.51 4.58 4.02 4.64;a2=polyfit(x,y,2);b2=polyval(a2,x);a4=polyfit(x,y,4);b4=polyval(a4,x);a6=polyfit(x,y,6);b6=polyval(a6,x);a9=polyfit(x,y,9);b9=polyval(a9,x);plot(x,b2,r-);hold onplot(x,b4,g-);hold onplot(x,b6,b-*);hold onplot(x
9、,b9,y-+);hold onplot(x,y,ko);title(含碳量 -时间曲线 );xlabel(时间t(分));ylabel(含碳量y(10-4));legend(二次拟合曲线, 四次拟合曲线, 六次拟合曲线 , 九次拟合曲线, 原函数点,);运行结果:警告: 多项式未正确设置条件。请添加具有不同 X 值的点,减少多项式的阶数,或者尝试按照 HELPPOLYFIT 中所述进行居中和缩放。 In polyfit at 75In leastway at 9 警告: 多项式未正确设置条件。请添加具有不同 X 值的点,减少多项式的阶数,或者尝试按照 HELPPOLYFIT 中所述进行居中和缩放。 In polyfit at 75In leastway at 11局部放大图