ktdrv
ktdrv

Reputation: 3673

Vector-valued function interpolation using NumPy/SciPy

Is there a way to interpolate a vector-valued function using NumPy/SciPy?

There are plenty of offerings that work on scalar-valued functions, and I guess I can use one of those to estimate each component of the vector separately, but is there a way to do it more efficiently?

To elaborate, I have a function f(x) = V, where x is scalar and V is a vector. I also have a collection of xs and their corresponding Vs. I would like to use it to interpolate and estimate V for an arbitrary x.

Upvotes: 11

Views: 6124

Answers (2)

Chris Flesher
Chris Flesher

Reputation: 1017

You could also vectorize the numpy.interp function like this:

interp = np.vectorize(np.interp, signature='(a),(b),(b)->(a)')
x = np.array([2.])
xp = np.linspace(0, 10, 10)
yp = np.random.randn(xp.size, 3)
interp(x, xp, yp.T).T

You could emulate scipy.interpolate.interp1d without the scipy dependency by wrapping the vectorized function using either lambda or functools.partial, for example:

interp1d = lambda x: np.vectorize(np.interp, signature='(a),(b),(b)->(a)')(x, xp, fp.T).T
interp1d(x)

Upvotes: 0

silvado
silvado

Reputation: 18167

The interpolation function scipy.interpolate.interp1d also works on vector-valued data for the interpolant (not for vector-valued argument data though). Thus, as long as x is scalar, you can use it directly.

The following code is a slight extension of the example given in the scipy documentation:

>>> from scipy.interpolate import interp1d
>>> x = np.linspace(0, 10, 10)
>>> y = np.array([np.exp(-x/3.0), 2*x])
>>> f = interp1d(x, y)
>>> f(2)
array([ 0.51950421,  4.        ])
>>> np.array([np.exp(-2/3.0), 2*2])
array([ 0.51341712,  4.        ])

Note that 2 is not in the argument vector x, thus the interpolation error for the first component in y in this example.

Upvotes: 8

Related Questions