基于matlab最小二乘曲线拟合
[记m=离散点的个数-1,k为拟合曲线的次数,r为平方误差,Ga=D为法方程]
x=-1.0:0.5:2.0;y=[-4.447,-0.452,0.551,0.048,-0.447,0.549,4.552];
plot(x,y,’*’)
xlabel(‘x轴’)
ylabel(‘y轴’);
hold on;
m=6;k=3;
G=zeros(k+1);
for j=1:k+1
for i=1:k+1
for n=1:m+1;
G(j,i)=G(j,i)+x(n)^(j+i-2)
end
end
end;
D=[0,0,0,0];
for j=1:k+1
for i=1:m+1
D(j)=D(j)+y(i)*x(i)^(j-1)
end
end
D=D’;
a=inv(G)*D;
x=[-1.0:0.0001:2.0];
z=a(1)+a(2)*x+a(3)*x.2+a(4)*x.3;
plot(x,z);
legend(‘离散点’,‘z=a(1)+a(2)*x+a(3)*x.2+a(4)*x.3’);
title(‘拟合图’);
x=[-1.0:0.5:2.0];
r=sum((z-y).^2)