Julia version of Matlab function interp1

If you want to use Interpolations.jl (a pure julia implementation), but stick with a familiar syntax you can create a reusable wrapper. I’m sure this could be improved, but here is an example that contains the same basic functionality as the matlab version including extrapolation options. Note that Interpolations has way many more options for spline degree, boundary conditions, and grid representation if you want to customize further.

using Interpolations

function interp1(xpt, ypt, x; method="linear", extrapvalue=nothing)

    if extrapvalue == nothing
        y = zeros(x)
        idx = trues(x)
    else
        y = extrapvalue*ones(x)
        idx = (x .>= xpt[1]) .& (x .<= xpt[end])
    end
    
    if method == "linear"
        intf = interpolate((xpt,), ypt, Gridded(Linear()))
        y[idx] = intf[x[idx]]

    elseif method == "cubic"
        itp = interpolate(ypt, BSpline(Cubic(Natural())), OnGrid())
        intf = scale(itp, xpt)
        y[idx] = [intf[xi] for xi in x[idx]]
    end
    
    return y
end
9 Likes