[转载][转载]曲线拟合的MATLAB实现
函数插值与曲线拟合
1、函数插值
method:nearest、linear、spline、cubic
例:
clear
echo on
x=-2:0.4:2;
y=[2.8 2.96 2.54 3.44 3.565.4
6.0 8.7 10.1 13.3 14.0];
t=-2:0.01:2;
nst=interp1(x,y,t,'nearest');
plot(x,y,'r*',t,nst)
title('最临近点插值')
lnr=interp1(x,y,t,'linear');
figure(2)
plot(x,y,'r*',t,lnr,'b:')
title('线性插值')
spl=interp1(x,y,t,'spline');
figure(3)
plot(x,y,'r*',t,spl)
title('样条插值')
cbc=interp1(x,y,t,'cubic');
figure(4)
plot(x,y,'r*',t,cbc,'k-')
title('三次插值')
2、曲线拟合
多项式拟合:polyfit(x,y,m) 线性:m=1,二次:m=2, …
例:
x=0:0.1:1;
y=[-0.447 1.978 3.28 6.16 7.08 7.347.66 9.56 9.48 9.30 11.2];
A=polyfit(x,y,2)
Z=polyval(A,x);
Plot(x,y,’r*’,x,z,’b’)
%多项式拟合函数polyfit示例
x=[0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1];
y=[-0.4471 0.978 3.28 6.16 7.08 7.34 7.66 9.56 9.48 9.30 11.2];
n=2;%polynomial order
p=polyfit(x, y, n);
%polyfit 的输出是一个多项式系数的行向量。
%其解是y = -9.8108x2+20.1293x-0.0317。为了将曲线拟合解与数据点比较,
xi=linspace(0, 1, 100);%x-axis data for plotting
z=polyval(p, xi);%polyval 求多项式值
plot(x, y, ' o ' , x, y, xi, z, ' : ' )
xlabel('x')
ylabel('y=f(x)')
title('Second Order Curve Fitting')
//最小二乘法曲线拟合
typedef CArrayCDoubleArray;
BOOL CalculateCurveParameter(CDoubleArray *X,CDoubleArray *Y,long
M,long N,CDoubleArray *A)
{
}
*%只考虑线性拟合*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
*%原始数据
*
t = [0 .3 .8 1.1 1.6
2.3]';
y = [0.5 0.82 1.14 1.25 1.35
1.40]';
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
*%多项式拟合
*