实验目的及要求:
1、会在Matlab平台上进行样条插值; 2、会在Matlab平台上进行最小二乘拟合。 | ||||||||||||||||||
实验内容: 1、利用spline函数绘制【0,10】内步长为1的插值节点处的的样条曲线。 2、根据下列数据三转角方程法构造三次样条函数S(x),,并写出表达式。
3、利用polyfit函数作三次,四次多项式拟合,并描绘拟合曲线。拟合数据如下: | ||||||||||||||||||
实验步骤与程序:
x=0:10; y=sin(x); xx=0:0.25:10; yy=spline(x,y,xx) plot(x,y,'+',xx,yy) hold on x=0:10; y=1./(1+25*x.^2); xx=0:1:10; yy=spline(x,y,xx); plot(x,y,'*',xx,yy)
被调用的san_zhuan_jiao.m文件 function [a,c,b,A,dY,s1,sk,sn] = san_zhuan_jiao(x,y,x0,y0,dy0,dyn) n = length(x); A = zeros(n-1,n-1); a = zeros(n-1,1); b = zeros(n-1,1); c = zeros(n-1,1); h = zeros(n-1,1); h0 = x(1) - x0 ; for i = 1:n-1 h(i) = x(i+1)-x(i); end a(1) = h0/(h0 + h(1)); c(1) = 1-a(1); b(1) = 3*((c(1)*(y(1)-y0)/h0)+a(1)*(y(2)-y(1))/(h(1))); for i = 2:n-1 a(i) = h(i-1)/(h(i-1)+h(i)) c(i) = i-a(i); b(i) = 3*(c(i)*(y(i)-y(i-1)/h(i-1))+a(i)*(y(i+1)-y(i))/h(i)) end b(1) = b(1)-c(1)*dy0; b(n-1) = b(n-1)-a(n-1)*dyn; A(1,1) = 2; A(1,2) = a(1); for i = 2:n-2 A(i,i) = 2; A(i,i+1) = a(i); A(i,i-1) = c(i); end A(n-1,n-1) = 2; A(n-1,n-1) = c(n-1); dY = A\b; syms X s1=y0*(h0-2*x0+2*X)*(X-x(1))^2/h0^3+y(1)* (h0+2*x(1)-2*X)*(X-x0)^2/h0^3+dy0*(X-x0)*(X-x(1))^2/h0^2+dY(1)*(X-x(1))*(X-x0)^2/h0^2; for k=2:n-1 sk=y(k-1)*((h(k-1)-2*x(k-1)+2*X)*(X-x(k))^2)/(h(k-1)^3)+y(k)*((h(k-1)+2*x(k)-2*X)*(X-x(k-1))^2)/(h(k-1)^3)+dY(k-1)*((X-x(k-1))*(X-x(k))^2)/(h(k-1)^2)+dY(k)*((X-x(k))*(X-x(k-1))^2)/(h(k-1)^2); end sn=y(n-1)*(h(n-1)-2*x(n-1)+2*X)*(X-x(n))^2/h(n-1)^3+y(n)* (h(n-1)+2*x(n)-2*X)*(X-x(n-1))^2/h(n-1)^3+dY(n-1)*(X-x(n-1))*(X-x(n))^2/h(n-1)^2+dyn*(X-x(n))*(X-x(n-1))^2/h(n-1)^2;
x0=-1;y0=-1;x=[0 1 3];y=[1 3 5]; dy0=6;dyn=1; [a,c,b,A,dY,s1,sk,sn]=san_zhuan_jiao(x,y,x0,y0,dy0,dyn)
x=0.1:0.1:0.9; y=[5.1234 5.3067 5.5687 5.9375 6.4370 7.0978 7.9778 9.0253 10.3627]; a1=polyfit(x,y,3) a2=polyfit(x,y,4) x1=0.1:0.1:0.9; y1=a1(4)+a1(3)*x1+a1(2)*x1.^2+a1(1)*x1.^3; %(y1=polyval(a1,x1) y2=a2(5)+a2(4)*x1+a2(3)*x1.^2+a2(2)*x1.^3+a2(1)*x1.^4; %(y2=polyval(a2,x1) plot(x,y,'*') hold on %三次多项式拟合 plot(x1,y1,'r-') hold on %四次多项式拟合 plot(x1,y2,'g^') | ||||||||||||||||||
运行结果:
| ||||||||||||||||||
结果分析与讨论: 1.spline函数只能实现非节点边界和约束导数的第二边界条件,可以实现一维或者高维的曲线插值。 2.polyfit函数是matlab中用于进行曲线拟合的一个函数。其数学基础是最小二乘法曲线拟合原理。 3.三次样条插值,是通过一系列形值点的一条光滑曲线,数学上通过求解三弯矩方程组得出曲线函数组的过程 |