1

It seems a few relevant questions here didn't give me the answer I want.

So I have a 2D look up table which is a 2D grid with values at grid coordiates. For example, such table can be generated by code below:

xx, yy = np.meshgrid(np.arange(100), np.arange(100))
zz = some_function(xx, yy)

now I have a list of coordinates of scattered points on the grid, for example, I can generate such coordinates by:

xs = np.random.rand(10) * 100
ys = np.random.rand(10) * 100

scattered_points = [(x, y) for x, y in zip(xs, ys)]

How can I interpolate out the z value for these 10 points? I only find out that I can do this by searching the neighboring grid points of (x, y) and perform interpolation there. It is fine for a few points but I just wonder if there is a better/pythonic way to do that using numpy/scipy.

shelper
  • 10,053
  • 8
  • 41
  • 67

2 Answers2

1

This should work for what you describe. (Updated)

from scipy.interpolate import interp2d
import numpy as np

xx, yy = np.meshgrid(np.arange(100), np.arange(100))
zz = some_function(xx,yy)

f = interp2d(xx, yy, zz, kind='cubic')

xs = np.random.rand(10) * 100
ys = np.random.rand(10) * 100
zs = np.zeros_like(xs)

for i in range(xs.shape[0]):
    zs[i]=f(xs[i],ys[i])
Anger Density
  • 332
  • 1
  • 3
  • 17
  • it actually does not work as expected, it basically generate a 10x10 grid using 10 xs and 10 ys, thus what it returns is a zs of size 10x10, not of size 10 – shelper Aug 02 '19 at 20:17
  • Updated the code to do (hopefully) what you describe. – Anger Density Aug 02 '19 at 20:25
  • that will work but performance won't be nice... i was looking for a way to vectorize it without loops 'cus i was trying to interpolate millions of points... Thanks anyway! – shelper Aug 02 '19 at 20:31
1

This uses an internal loop, but it is short and direct:

scattered_points = np.squeeze([f(x, y) for x, y in zip(xs, ys)])

The np.squeeze() is to match the dimensions of the input.

A. Wimmers
  • 11
  • 3