最小二乘拟合

拟合函数

function C = lspoly(X,Y,M)
%This funciton implements the Least Squares Polynomial
%By abcat at 2014.5.7
%Input  -X is the 1*n abscissa vector
%       -Y is the 1*n ordinate vecotr
%       -M is the degree of the Least-Squares Polynomial
%Output -C is the coefficient list for the polynomial
n=length(X);
B=zeros(1:M+1);
F=zeros(n:M+1);
%File the columns of F with the powers of x
for k=1:M+1
    F(:,k)=X'.^(k-1);
end
%Solve the linear system
A=F'*F;
B=F'*Y';
C=A\B
C=flipud(C);

主程序

%输入数据
x = [3.46   3.36   3.30   3.19   3.10   3.00   2.92  2.83   2.75   2.68];
y = [9.4141   9.0832   8.8945   8.5350   8.1286  7.7160   7.3556   6.9819   6.6267   6.2953];
%最小二乘拟合,参数分别是横、纵轴数据,拟合次数
c=lspoly(x,y,2);
y1=polyval(c,x);
%绘图
plot(x,y1)
hold on
plot(x,y,'ro')
legend('Curve Fitting','Experimental Data')
grid on
xlabel('Abscissa Vector')
ylabel('Ordinate Vector')

posted @ 2014-05-08 13:40  冷风一夜  阅读(326)  评论(0编辑  收藏  举报