function spline_example(npts) clf % Run this example with npts = 5 to show a case when the shape % preserving cubic spline works better than the regular cubic spline % and with npts = 6 to show a case where the regular cubic spline % works better than the shape preserving cubic spline. Also show what % happens with npts = 7 and 8 and point out that the shape preserving % cubic spline is not a good way to go if the function being fitted % is known to have second derivative (or higher) continuity. % First create data points for a simple sine curve x = linspace(0,2*pi,npts); y = sin(x); plot(x,y,'kx') legend('Original points') axis([0 2*pi -1.5 1.5]) hold on pause % First fit these data points using the spline command xtrue = linspace(0,2*pi,101); ytrue = sin(xtrue); xfit = xtrue; yfit = spline(x,y,xfit); plot(xtrue,ytrue,'k-',xfit,yfit,'r-') legend('Original points','Original curve','Cubic spline fit') pause % Now fit the same data using the interp1 command with % a shape preserving cubic spline xfit2 = xtrue; yfit2 = interp1(x,y,xfit2,'pchip'); plot(xfit2,yfit2,'b-') legend('Original points','Original curve','Cubic spline fit','Shape preserving fit')