Back to M331: Matlab Codes, Notes and Links

Spline Interpolation in Matlab

Assume we want to interpolate the data (1,20), (3,17), (5,23), (7,19) using splines, and then evaluate the interpolated function at x=2, 4, 6. In Matlab, we first define the data vectors:

>> x=[1 3 5 7];y=[20 17 23 19];xi=[2 4 6];

(1) Linear Splines:

The interpolated y-data are found by executing

>> yi=interp1(x,y,xi)

yi =

  18.50000000000000  20.00000000000000  21.00000000000000

(2) Cubic Splines:

Here the interpolated data are found by executing

>> yi=interp1(x,y,xi,'spline')

yi =

  16.18750000000000  20.06250000000000  23.43750000000000

We can also generate a large array of interpolated data points for
plotting the interpolation function (don't forget the semicolon)

>> xp=linspace(1,7,100);yp=interp1(x,y,xp,'spline');

and plot function and data (using a script):

plot(xp,yp,'k',x,y,'ko',xi,yi,'kv')
xlabel('x-values'),ylabel('y-values'),
legend('interpolated graph','given data','interpolated data')
axis([1 7 15 24])