Help with interpolation

I’m looking for a function similar to interp1 in Matlab, and browsing the web I found the following piece of code that supposedly do the job:

using Interpolations
function interp1(X, V, Xq)
    knots = (X,)
    itp = interpolate(knots, V, Gridded(Linear()))
    itp[Xq]
end

To check if it is working I tried the following example:

X = [1,2,3,4,5,6,7,8,9,10];
V = [X.^2 X.^3 X.^4];
Xq = [1.5 1.75; 7.5 7.75]
interp1(X,V,Xq)

But I get the following error

ERROR: MethodError: no method matching interpolate(::Tuple{Array{Float64,1}}, ::Array{Float64,2}, ::Gridded{Linear})

What I’m doing wrong here? Is there another way to replicate interp1 in Julia?

Source of interp1 function: http://robblackwell.com/julia/index.html

interpolate expects that your knot locations should be of the same dimension as the samples to be interpolated, but your X is a 1-dimensional vector, while V is a two-dimensional matrix. You can try this yourself with a 1-dimensional interpolation:

x = 1:10
v = x.^2
knots = (x,)
itp = interpolate(knots, v, Gridded(Linear()))
xq = [1.5, 1.75, 7.5, 7.75]
itp.(xq)

which gives:

julia> itp.(xq)
4-element Array{Float64,1}:
  2.5
  3.25
 56.5
 60.25

Note the use of itp.(xq) which uses Julia’s built-in broadcasting to compute itp(y) for each y in xq.

As for your 2d example, I’m sure there’s a way to get the output you’re looking for, but I’m having trouble figuring out what the intended behavior is from your code. What result are you expected from interpolating a 2D matrix V with a 1D vector of knots X?

1 Like

Hi, thank you for your reply.

The example I provided is taken from Matlab. I’m just checking if both functions will produce similar results. The expected output would be a 3D array of size (2,2,3).