matlab曲线拟合实例

曲线拟合

已知数据 x y 1 10 3 5 5 2 6 1 7 1 8 2 9 3 10 4 求二次拟合多项式 解:(一)最小二乘法MATLAB编程: function p=least_squar(x,y,n,w) if nargin<4 w=1 end

if nargin<3 n=1 end

m=length(y); X=ones(1,m) if m<=n error end

for i=1:n X=[(x.^i);X] end

A=X*diag(w)*X';b=X*(w.*y)';p=(A\\b)' 输入:

x=[1 3 5 6 7 8 9 10]; y=[10 5 2 1 1 2 3 4] p=least_squar(x,y,2) 运行得: p =

0.2763 -3.6800 13.4320

故所求多项式为:s(x)=13.432-3.68x+0.2763x (二)正交多项式拟合MATLAB编程: function p=least_squar2(x,y,n,w) if nargin<4 w=1; end

if nargin<3 n=1; end

m=length(x); X=ones(1,m); if m<=n error end

for i=1:n X=[x.^i;X]; end

A=zeros(1,n+1);

2

A(1,n+1)=1; a=zeros(1,n+1); z=zeros(1,n+1); for i=1:n

phi=A(i,:)*X;t=sum(w.*phi.*phi); b=-sum(w.*phi.*x.*phi)/t a(i)=sum(w.*y.*phi)/t; if i==1 c=0;else c=-t/t1; end t1=t

for j=1:n z(j)=A(i,j+1); end

z(n+1)=0 if i==1

z=z+b*A(i,:); else

z=z+b*A(i,:)+c*A(i-1,:); end

A=[A;z]; end

phi=A(n+1,:)*X;t=sum(w.*phi.*phi); a(n+1)=sum(w.*y.*phi)/t; p=a*A; 输入:

x=[1 3 5 6 7 8 9 10]; y=[10 5 2 1 1 2 3 4]; p=least_squar2(x,y,2) 运行得: b =

-6.1250 t1 = 8 z =

0 1 0 b =

-4.9328 t1 =

64.8750 z =

1.0000 -6.1250 0 p =

0.2763 -3.6800 13.4320

故所求多项式为:s(x)=13.432-3.68x+0.2763x

2

(三)用现成的MATLAB函数polyfit( )拟合; 输入:

x=[1 3 5 6 7 8 9 10]; y=[10 5 2 1 1 2 3 4]; p=polyfit(x,y,2) 运行得: p =

0.2763 -3.6800 13.4320

联系客服:779662525#qq.com(#替换为@) 苏ICP备20003344号-4