% MATLAB Built-In Function interp1 and spline % % YI = INTERP1(X, Y, XI, METHOD) specifies alternate methods. % The default is linear interpolation. Use an empty matrix [] % to specify the default. Available methods are: % 'nearest' - nearest neighbor interpolation % 'linear' - linear interpolation % 'spline' - piecewise cubic spline interpolation (SPLINE) % 'pchip' - shape-preserving piecewise cubic Hermite interpolation % % Example : interp1 % Consider the data for x = -2:0.5:2 generated by y = (1/4)x^4 - (1/2)x^2. % Interpolate and plot using the four different methods listed in interp1. % % specify the x array starting from -2 to 2 with increment of 0.5 x = -2:0.5:2; % specify the y array using the formula y = (1./4.) * x.^4 - (1./2.) * x.^2; % generate a row vector of 100 evenly spaced points between -2 and 2 xi = linspace(-2, 2); % call interp1 with nearest neighbor interpolation ynear = interp1(x, y, xi, 'nearest'); % call interp1 with linear interpolation ylin = interp1(x, y, xi, 'linear'); % call interp1 with piecewise cubic Hermite interpolation ypc = interp1(x, y, xi, 'pchip'); % call interp1 with piecewise cubic spline interpolation yspl = interp1(x, y, xi, 'spline'); % start drawing the four plots side-by-side subplot(2, 2, 1), plot(xi, ynear, x, y, 'o'), title('Nearest neighbor interpolation') axis([-2 2 -0.5 2]) hold on subplot(2, 2, 2), plot(xi, ylin, x, y, 'o'), title('Linear interpolation') axis([-2 2 -0.5 2]) subplot(2, 2, 3), plot(xi, ypc, x, y, 'o'), title('Piecewise cubic Hermite interpolation') axis([-2 2 -0.5 2]) subplot(2, 2, 4), plot(xi, yspl, x, y, 'o'), title('Cubic spline interpolation') axis([-2 2 -0.5 2])