7

次の Matlab ステートメントに相当する Python を探しています。

vq interp1(x,y, xq,'nearest','extrap')

interp(xq, x, y)線形補間/補外に完全に機能するように見えます。

私も見ました

F = scipy.interpolate.interp1d(x, y, kind='nearest')

最も近い方法では完全に機能しますが、外挿は実行されません。

他に見落としているものはありますか?ありがとう。

4

2 に答える 2

7

最も近い補間を使用して外挿する線形補間の場合は、 を使用します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()

ここに画像の説明を入力

于 2014-01-08T18:24:56.373 に答える