Python中类似于Matlab的interp函数
有人能解释一下如何在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 个回答
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
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])