Created
July 20, 2017 13:25
-
-
Save michaelosthege/e20d242bc62a434843b586c78ebce6cc to your computer and use it in GitHub Desktop.
vectorized linear interpolation in numpy
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import numpy | |
from matplotlib import pyplot | |
def interpolate(x_fix, y_fix, x_var): | |
x_repeat = numpy.tile(x_var[:,None], (len(x_fix),)) | |
distances = numpy.abs(x_repeat - x_fix) | |
x_indices = numpy.searchsorted(x_fix, x_var) | |
weights = numpy.zeros_like(distances) | |
idx = numpy.arange(len(x_indices)) | |
weights[idx,x_indices] = distances[idx,x_indices-1] | |
weights[idx,x_indices-1] = distances[idx,x_indices] | |
weights /= numpy.sum(weights, axis=1)[:,None] | |
print(weights.round(2)) | |
y_var = numpy.dot(weights, y_fix.T) | |
return y_var | |
x_fix = numpy.arange(0,10,1.1) # x for which y is available | |
y_fix = x_fix**2 | |
x_var = numpy.array([1.2,2.3,6.7,7.2]) # x for which y is desired | |
y_var = interpolate(x_fix, y_fix, x_var) | |
print("x_fix: {}".format(x_fix)) | |
print("y_fix: {}".format(y_fix)) | |
print("x_var: {}".format(x_var)) | |
print("y_var: {}".format(y_var)) | |
pyplot.figure() | |
pyplot.plot(x_fix, y_fix, label="original") | |
pyplot.plot(x_var, y_var, label="interpolation") | |
pyplot.legend() | |
pyplot.show() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment