function moments=RungeNatSpline(n) %This routine calculates the second-derivative moments %for the Runge example y = 1/(x^2 +1), with equally-spaced %knot points, and draws the natural-spline approx. xdraw=[-5:0.04:5]'; ydraw=1./(xdraw.^2+1); plot(xdraw,ydraw,'r') hold on %Create the Runge data points. hstep=10/(n-1); x=zeros(n,1); for ii=1:n x(ii)=-5+(ii-1)*hstep; end y=1./(x.^2+1); %Calculate the natural-spline moments. We ought to do a proper %tri-diagonal solver, but I can't be bothered. moments=zeros(n,1); A=zeros(n-2,n-2); %Give the natural-spline conditions on the end moments. moments(1)=0; moments(n)=0; %Solve the spline moment conditions. for ii=1:n-2 if ii>1 A(ii-1,ii)=1; end A(ii,ii)=4; if ii=x(ii) if xdraw(iplot)<=x(ii+1) jval=ii; end end end x1min=x(jval+1)-xdraw(iplot); xmin=xdraw(iplot)-x(jval); term1=(moments(jval)*x1min^3+moments(jval+1)*xmin^3)/(6*hstep); term2=(y(jval)/hstep-moments(jval)*hstep/6)*x1min; term3=(y(jval+1)/hstep-moments(jval+1)*hstep/6)*xmin; splin(iplot)=term1+term2+term3; end plot(xdraw,splin,'b') hold off