# Nearest Neighbour Interpolation with Interpolations.jl

I’ve been using the Interpolations.jl package quite happily for a while now. I almost exclusively make use of the convienience constructors for both linear and cubic (mostly 1d) interpolation. I’ve only just recently come accross an aplication whereby I need to use nearest neighbour interpolation, however I just can’t get it to work. Can anyone she any light on what I’m doing wrong. Sorry for presenting such a pedestrian question!

``````using Interpolations
using Plots

a = range(0,2*pi,length=8);
f(x) = cos(x);

x = range(0,2*pi,length=100);

linear = LinearInterpolation(a, f.(a), extrapolation_bc = Line());
cubic = CubicSplineInterpolation(a, f.(a), extrapolation_bc = Line());
nearest = interpolate(a, BSpline(Constant()));

plt = plot(x, f.(x), label="Cosine")
plt = plot!(x, linear.(x), label="Linear Interp")
plt = plot!(x, cubic.(x), label="Cubic Interp")
plt = plot!(x, nearest.(x), label="Nearest")
plt = plot!(title="Interpolation Schemes", legend = :bottomleft)

``````

This throws a bounds error. The example works fine for linear and cubic interpolation. Many thanks.

I think you want to use Scaled BSplines.

``````linear = scale(interpolate(f.(a), BSpline(Linear())), a)
cubic = scale(interpolate(f.(a), BSpline(Cubic(Line(OnGrid())))), a)
nearest = scale(interpolate(f.(a), BSpline(Constant())), a)
``````

This seems to work (see SO):

``````nearest = interpolate((a,), f.(a), Gridded(Constant()))
`````` 2 Likes

Perfect, thanks. I tried the same but couldn’t get it to work. Probably a syntax related issue,