[Numpy-discussion] Vectorization of variant of piecewise or interpolation function

Seth Ghandi seth.ghandi.2017 at gmail.com
Sun Oct 15 22:16:47 EDT 2017


Hi everybody,

I am new to newpy and am trying to define a variant of piecewise or zero holder interpolation function, say ZeroOrderInterpolation(t,a), where t is an 1D array of size, say p, consisting of real numbers, and a is a 2D array of size, say nxm, with first column consisting of increasing real numbers. This function should return an array, say y, of size px(m-1) such that y[i,:] is equal to
a[n,1:] if a[n,0] <= t[i], and
a[k,1:] if k < n and a[k,0] <= t[i] < a[k+1,0].
Note that t[0] is assumed to be at least equal to a[0,0].

I have the following script made of "for loops" and I am trying to vectorize it so as to make it faster for large arrays.

def ZeroOrderInterpolation(t,a):
  import numpy as np
  p = t.shape[0]
  n, m = a.shape
  if n == 1:
    return a[0,1:]
  y = np.zeros((p,m-1))
  for i in range(p):
    if a[n-1,0] <= t[i]:
      y[i] = a[n-1,1:]
    else:
      for j in range(n-1):
        if (a[j,0] <= t[i]) and (t[i] <= a[j+1,0]):
          y[i] = a[j,1:]
  return y

import numpy as np
t = np.array([0.5,1,1.5,2.5,3,10])
table = np.array([[0,3],[1,0],[2,5],[3,-1]])
ZeroOrderInterpolation(t,table)

[Out]: array([[ 3.],
       [ 0.],
       [ 0.],
       [ 5.],
       [-1.],
       [-1.]])


Any help for a vectorization "à la numpy" of this fucntion will be apprecaited.

Best regards,


More information about the NumPy-Discussion mailing list