Python中的interp函数类似于Matlab。

4
有人可以解释一下如何在Python中使用插值函数来处理现有的数组吗?类似于Matlab中存在的方式。
示例: x =
 1
 2
 3
 4
 5
 6
 7
 8
 9
10

interp(x,2)

答案 =

1.0000
1.4996
2.0000
2.4993
3.0000
3.4990
4.0000
4.4987
5.0000
5.4984
6.0000
6.4982
7.0000
7.4979
8.0000
8.4976
9.0000
9.4973
10.0000
10.4970

我希望有一个Python函数完全按照这个做法,即在保持原点不变的情况下添加更多点。


作为函数调用中的第二个参数,2代表什么意思? - Lily Mara
@NateMara:增加数据点的次数是多少? - Hugh Bothwell
可能是线性插值 - Python的重复问题。 - MattG
2个回答

1

有几个问题需要提出:

  • 您只是在看线性插值(即使用直线段“连接点”)吗?这很简单但有些不好。您可以使用更高阶曲线(即双三次样条曲线)获得更好的结果,但为此需要提供更多信息以确定唯一的解决方案(即端点一阶导数)。

  • 您是否希望在平滑曲线的同时将其精确地穿过给定点,还是只需穿过给定点?

  • 您的输入点是否均匀分布(即沿x轴)?

  • 您的数据显示不仅进行了插值,还进行了外推(即您的最后一个点超出了数据范围)-这实际上是您想要的吗?

Matlab文档说:“interp将0插入原始信号,然后对扩展序列应用低通插值滤波器。”。


编辑:我认为最接近的相当于scipy.interpolate.interp1d - 请参见http://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.interp1d.html#scipy.interpolate.interp1d

您可以这样制作包装器:

import numpy as np
from scipy.interpolate import interp1d

def interp(ys, mul):
    # linear extrapolation for last (mul - 1) points
    ys = list(ys)
    ys.append(2*ys[-1] - ys[-2])
    # make interpolation function
    xs = np.arange(len(ys))
    fn = interp1d(xs, ys, kind="cubic")
    # call it on desired data points
    new_xs = np.arange(len(ys) - 1, step=1./mul)
    return fn(new_xs)

它然后像这样工作

>>> interp([1,2,3,4,5,6,7,8,9,10], 2)
array([  1. ,   1.5,   2. ,   2.5,   3. ,   3.5,   4. ,   4.5,   5. ,
         5.5,   6. ,   6.5,   7. ,   7.5,   8. ,   8.5,   9. ,   9.5,
        10. ,  10.5])

是的,我的输入点是均匀分布的。我只想在已有的点之间均匀添加更多的点。例如,如果我的数据是1,1.5,2,2.5...,我希望得到1,1.25,1.5,1.75,2,2.25,2.50...请注意,我的原始点已经存在,我只是在这里添加了更多的点。我不关心外推。我的目标是在自变量轴上获得更多的值,以便更好地平滑函数。由于我的x值已经指定,所以不能使用任意生成器,如linspace。 - Archis
@Archis:请看我刚添加的包装函数。您可以通过指定interp1d(kind =)来更改所使用的插值函数;它目前正在使用分段三次样条插值。 - Hugh Bothwell
@HughBothwell :我想使用Matlab的interp2函数来处理一个封闭轮廓。请问我应该使用哪个Python函数? - Gunjan naik

0
您可以通过以下方式获得类似于Matlab的interp()函数的结果:
def interpolate_1d_vector(vector, factor):
    """
    Interpolate, i.e. upsample, a given 1D vector by a specific interpolation factor.
    :param vector: 1D data vector
    :param factor: factor for interpolation (must be integer)
    :return: interpolated 1D vector by a given factor
    """
    x = np.arange(np.size(vector))
    y = vector
    f = scipy.interpolate.interp1d(x, y)

    x_extended_by_factor = np.linspace(x[0], x[-1], np.size(x) * factor)
    y_interpolated = np.zeros(np.size(x_extended_by_factor))

    i = 0
    for x in x_extended_by_factor:
        y_interpolated[i] = f(x)
        i += 1

    return y_interpolated

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接