matlab中的nearest,在Python中使用’nearest’方法进行外部开发

对于使用最近插值进行外推的线性插值,请使用numpy.interp.它默认情况下这样做.

例如:

yi = np.interp(xi, x, y)

否则,如果您只想在最近处进行最近插值,如您所述,您可以用简短但效率低下的方式进行:(如果需要,可以将其设为单行插值)

def nearest_interp(xi, x, y):

idx = np.abs(x - xi[:,None])

return y[idx.argmin(axis=1)]

或者使用searchsorted以更有效的方式:

def fast_nearest_interp(xi, x, y):

"""Assumes that x is monotonically increasing!!."""

# Shift x points to centers

spacing = np.diff(x) / 2

x = x + np.hstack([spacing, spacing[-1]])

# Append the last point in y twice for ease of use

y = np.hstack([y, y[-1]])

return y[np.searchsorted(x, xi)]

为了说明numpy.interp和上面最近的插值示例之间的区别:

import numpy as np

import matplotlib.pyplot as plt

def main():

x = np.array([0.1, 0.3, 1.9])

y = np.array([4, -9, 1])

xi = np.linspace(-1, 3, 200)

fig, axes = plt.subplots(nrows=2, sharex=True, sharey=True)

for ax in axes:

ax.margins(0.05)

ax.plot(x, y, 'ro')

axes[0].plot(xi, np.interp(xi, x, y), color='blue')

axes[1].plot(xi, nearest_interp(xi, x, y), color='green')

kwargs = dict(x=0.95, y=0.9, ha='right', va='top')

axes[0].set_title("Numpy's $interp$function", **kwargs)

axes[1].set_title('Nearest Interpolation', **kwargs)

plt.show()

def nearest_interp(xi, x, y):

idx = np.abs(x - xi[:,None])

return y[idx.argmin(axis=1)]

main()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值