《Lagrange插值MATLAB源程序(14页).doc》由会员分享,可在线阅读,更多相关《Lagrange插值MATLAB源程序(14页).doc(15页珍藏版)》请在taowenge.com淘文阁网|工程机械CAD图纸|机械工程制图|CAD装配图下载|SolidWorks_CaTia_CAD_UG_PROE_设计图分享下载上搜索。
1、-Lagrange插值MATLAB源程序function y=lagrange(x0,y0,x); % x0自变量取值向量已知 y0为已知对应x0的函数取值,x为要求插值点坐标n=length(x0); m=length(x); for i=1:m z=x(i); s=0.0; for k=1:n p=1.0; for j=1:n if j=k p=p*(z-x0(j)/(x0(k)-x0(j); %插值基函数 end end s=p*y0(k)+s; %lagrange插值多项式 end y(i)=s;end 测试:x0=0:2 y0=2 3 5 x=0.5Lagrange(x0,y0,x)
2、x0=0:2 y0=2 3 5 x=0:0.01:2Lagrange(x0,y0,x) Newton插值MATLAB源程序function f=Newton(x,y,x0) syms t; n = length(x); c(1:n) = 0.0; f = y(1); y1 = 0; l = 1; for(i=1:n-1) for(j=i+1:n) y1(j) = (y(j)-y(i)/(x(j)-x(i); end c(i) = y1(i+1); l = l*(t-x(i); f = f + c(i)*l; simplify(f); y = y1; if(i=n-1) if(nargin =
3、3) f = subs(f,t,x0); else f = collect(f); end end endtest: x=1 -1 2 y=0 -3 4 x0=-1:0.1:2Newton(x,y,x0)分段插值MATLAB源程序function y = div_linear(x0,y0,x,n) for i = 1:n-1 if (x = x0(i) & (x =j t(i,j)=(t(i,j-1)-t(i-1,j-1)/(x(i)-x(i-j+1); end end end for k=1:n s=1; m=1; for j=1:k if jnewtonNewton插值MATLAB源程序f
4、unction yi=newton(x,y,xi) m=length(x);n=length(y); if m=n error(x and y must same);end f=zeros(n+1,1); k=2; f(1)=y(1) while k=n+1 f(1)=y(k);k,x(k) for i=1:k-1 if i=k-1 f(i+1)=(f(i)-y(i)/(x(k)-x(i); end end cs(i)=f(i+1); y(k)=f(k); k=k+1;end cfwh=0; for i=1:n-2 w=1; for j=1:i w=w*(xi-x(j); end cfwh=c
5、fwh+cs(i)*w; end yi=y(1)+cfwh;x=0:2 y=2 3 5 xi=0.5newton(x,y,xi)Newton2)functionf=Newton(x,y,x0)symst;if(length(x)=length(y) n=length(x);c(1:n)=0.0;else disp(x和y的维数不相等!);return;endf=y(1);y1=0;l=1;for(i=1:n-1)for(j=i+1:n) y1(j)=(y(j)-y(i)/(x(j)-x(i);end c(i)=y1(i+1);l=l*(t-x(i);f=f+c(i)*l;simplify(f)
6、;y=y1;if(i=n-1) if(nargin=3) f=subs(f,t,x0);else f=collect(f);%将插值多项式展开f=vpa(f,6);endend endx=0:2 y=2 3 5 x0=0.5Newton(x,y,x0) function=Newton(x,y,v)x=input(X数组=:);y=input(Y数组=:);v=input(插值点数值=:);n=length(x);t=zeros(n,n);u=0;fori=1:nt(i,1)=y(i);endforj=2:nfori=2:nifi=jt(i,j)=(t(i,j-1)-t(i-1,j-1)/(x(i)-x(i-j+1);endendendfork=1:ns=1;m=1;forj=1:kifjks=s*(v-x(j);endendm=s*t(k,k);u=u+m;enddisp(插值结果=);disp(u);endx=0:2 y=2 3 5 v=0.5newton(x,y,v) x0=1 -1 2 y0=0 -3 4 x=-1:0.1:2Lagrange(x0,y0,x)第 15 页-