多项式拟合.m文件
<PRE>% General Polynomial Fitting Methodfunction Ans=polyfit2(x,y,order)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Polynomial Fitting Method
% x,y are two set of data, and order is the
% max degree of fitting polynomial
%
% FangQ
% 2000/11/30
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
n=4
if nargin==3
n=order;
end
if size(x)~=size(y)
warning('Bad input data');
end
n=n+1;
a=zeros(1,n);
A=zeros(n);
Y=zeros(n,1);
for i=1:n
for j=1:n
A(i,j)=sum(x.^(i+j-2));
end
end
for i=1:n
Y(i,1)=sum(y.*x.^(i-1));
end
Ans=inv(A)*Y;
XI=min(x):min(diff(x))/3:max(x);
Poly=num2str(Ans(1));
for i=2:n
Poly=strcat(Poly,'+(',num2str(Ans(i)),'*x^',num2str(i-1),')');
end
disp(sprintf('Polynomial: \n\t %s',Poly));
FitError=sum((y-polyval(fliplr(Ans'),x)).^2);
disp(sprintf('\nTotal error is %f',FitError));
hold on;
plot(XI,polyval(fliplr(Ans'),XI),'r-',x,y,'o');
</PRE> 挺好用的,就是要注意换行,
要不粘贴时不太好整。
哈哈。
[ 本帖最后由 xinyuxf 于 2007-7-3 09:04 编辑 ]
页:
[1]