Search code examples
matlabplotinterpolationspline

Spline interpolation plot in Matlab


i'm trying to output few graphs in the same plot using different interpolations in order to find the y when x = 5 and mark that point with a red asterisk. I did the linear and it's working good (means i get a good plot) but when i'm trying to output the spline plot it doesn't work very well (as you can see it only shows a line of asterisks). i would appreciate some help with understanding why it is now working?

This is my code:

clc;
clear;
close all;

%variables
y = [101.3 106.6 109.4 114.7 116.9 118.2 123.7];
x = [1.69 3.67 4.37 5.45 5.84 6.05 6.90];

%Linear interpolate to get pressure at v = 5 [m/s]
pressure = interp1(x,y,5)

%Spline interpolate to get pressure at v = 5 [m/s]
xx = 1.69:6.90;
yy = spline(x,y,5)

s = interp1(x,y,xx,"spline");

%linear plot output
hold on;
plot(x,y,'b.-')
plot(5,pressure,'*')
grid on;

%spline plot output
hold on;
plot(x,y,'o')
plot(xx,yy,'*')

and the plot:plot for linear and spline


Solution

  • You’re plotting the single result of interpolating at 5, yy. You need to plot the result of the interpolation across the whole xx domain, s.

    You were also plotting your original data twice. I cleaned the plotting and comments a bit, to make things more precise.

    y = [101.3 106.6 109.4 114.7 116.9 118.2 123.7];
    x = [1.69 3.67 4.37 5.45 5.84 6.05 6.90];
    
    %Linear interpolate to get pressure at v = 5 [m/s]
    pressure = interp1(x,y,5)
    
    %Spline interpolate to get pressure at v = 5 [m/s]
    xx = 1.69:6.90;
    yy = spline(x,y,5)
    
    s = interp1(x,y,xx,"spline");
    
    %original data plot
    plot(x,y,'b.-')
    grid on
    
    %linear interpolation single point
    hold on
    plot(5,pressure,'*')
    
    %spline interpolation single point
    plot(5,yy,'square')
    
    %spline plot output
    plot(xx,s,'+')
    hold off
    

    Note that you’re actually performing the spline interpolation twice, once for spline and once for interp1(x,y,xx,'spline'). It might be cleaner to get the entire spline structure back from spline and extract your interpolated values from it using ppval:

    pp = spline(x,y);
    yy = ppval(pp,5);
    s = ppval(pp,xx);