Search code examples
julia

2D interpolation in Julia


I have two arrays of Float64: arr_x and arr_y. I have a 2D array arr_z storing some function z(x,y) computed on the set of points (x,y) with x in arr_x, y in arr_y.

How can I do a 2D interpolation of arr_z using arr_x and arr_y? That is, I would like a function itp_z(x,y) which does the equivalent of linear interpolation but now in 2D on the array arr_z.


Solution

  • Interpolations.jl should work for that:

    using Interpolations, Plots
    # Data
    x = range(-2, 3, length=20)
    y = range(3, 4, length=10)
    z = @. cos(x) + sin(y')
    # Interpolation object (caches coefficients and such)
    itp = LinearInterpolation((x, y), z)
    # Fine grid
    x2 = range(extrema(x)..., length=300)
    y2 = range(extrema(y)..., length=200)
    # Interpolate
    z2 = [itp(x,y) for y in y2, x in x2]
    # Plot
    p = heatmap(x2, y2, z2, clim=(-2,2), title="Interpolated heatmap")
    scatter!(p, [x for _ in y for x in x], [y for y in y for _ in x], zcolor=z[:]; lab="original data", clim=(-2,2))
    

    gives youenter image description here