% Applying Lagrange and cubic spline interpolation on Ruddy duck example % See Example 3 on pages 149-152 of Burden and Faires % Kartik's MATLAB session % September 17, 2007. % To run this demo, download this file into your MATLAB directory. % Start MATLAB and at the MATLAB prompt >> type % ruddyduck % You should get a plot as output % (x,f(x)) values from Table 3.17 x = [0.9 1.3 1.9 2.1 2.6 3.0 3.9 4.4 4.7 5.0 6.0 7.0 8.0 9.2 10.5 11.3 11.6 12.0 12.6 13.0 13.3]'; y = [1.3 1.5 1.85 2.1 2.6 2.7 2.4 2.15 2.05 2.1 2.25 2.3 2.25 1.95 1.4 0.9 0.7 0.6 0.5 0.4 0.25]'; % Generate a grid of points xgrid = 0.9:0.01:13.3; lgrid = length(xgrid); % Estimate the parameters for the natural spline using Kartik's MATLAB code spar = naturalcubicsplineInt(x,y); for i=1:lgrid, % Find the Lagrange interpolated value at xgrid(i) yLgrid(i) = lagrangeINT(x,y,xgrid(i)); index = find(x-xgrid(i) > 0); if isempty(index) == 0, index = index(1)-1; else index = 20; end val = (xgrid(i)-x(index)); % Find the natural spline interpolated value at xgrdi(i) ySgrid(i) = spar(4*(index-1)+1) + spar(4*(index-1)+2)*val + spar(4*(index-1)+3)*(val^2) + spar(4*(index-1)+4)*(val^3); end figure(1); % Plot the values. Compare this plot with Figures 3.12 and 3.13 in Burden % and Faires plot(xgrid,[yLgrid(:) ySgrid(:)]); legend('Lagrange interpolation', 'Cubic spline interpolation'); xlabel('x'); ylabel('f(x)'); title('Approximating the top profile of the Ruddy duck');