Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interpolate each row in matrix of x values

I want to interpolate between values in each row of a matrix (x-values) given a fixed vector of y-values. I am using python and essentially I need something like scipy.interpolate.interp1d but with x values being a matrix input. I implemented this by looping, but I want to make the operation as fast as possible.

Edit

Below is an example of a code of what I am doing right now, note that my matrix has more rows on order of millions:

import numpy as np
x = np.linspace(0,1,100).reshape(10,10)
results = np.zeros(10)
for i in range(10):
  results[i] = np.interp(0.1,x[i],range(10))
like image 982
matt Avatar asked Jun 18 '15 01:06

matt


1 Answers

As @Joe Kington suggested you can use map_coordinates:

import scipy.ndimage as nd

# your data - make sure is float/double
X = np.arange(100).reshape(10,10).astype(float)

# the points where you want to interpolate each row 
y = np.random.rand(10) * (X.shape[1]-1)
# the rows at which you want the data interpolated -- all rows
r = np.arange(X.shape[0])

result = nd.map_coordinates(X, [r, y], order=1, mode='nearest')

The above, for the following y:

array([ 8.00091648,  0.46124587,  7.03994936,  1.26307275, 1.51068952,
        5.2981205 ,  7.43509764,  7.15198457,  5.43442468,  0.79034372])

Note, each value indicates the position in which the value is going to be interpolated for each row.

Gives the following result:

array([  8.00091648,  10.46124587,  27.03994936,  31.26307275,
        41.51068952,  55.2981205 ,  67.43509764,  77.15198457,
        85.43442468,  90.79034372])

which makes sense considering the nature of the aranged data, and the columns (y) at which it is interpolated.

like image 140
Imanol Luengo Avatar answered Nov 14 '22 23:11

Imanol Luengo