首页 > 解决方案 > python中matlab的等效插值是什么?

问题描述

我想将代码从 matlab 重写为 python。在matlab中,我有以下内容:

interp1(TMP.time_hor, TMP.lane_hor, TMP.travel_time, 'next') % matlab

“下一个”是指哪个插值?通常默认是线性的。有一个 numpy 等价物吗?例如:

numpy.interp(x, xp, fp, left=None, right=None, period=None) # python

这是“线性”插值...

标签: pythonmatlabnumpyinterpolation

解决方案


哪个插值是指'next'?通常默认是线性的。有一个 numpy 等价物吗?

插值方法'next'插值到数据集中的下一个数据点(参见:https ://www.mathworks.com/help/matlab/ref/interp1.html )。

查看 NumPy 的文档(https://numpy.org/doc/stable/reference/generated/numpy.interp.html),看起来好像它们使用线性插值,所以如果你想要相同的输出,你只需要指定这在你的 MATLAB 命令中,如下所示:

interp1(TMP.time_hor, TMP.lane_hor, TMP.travel_time, 'linear')

话虽这么说,'linear'是 的默认插值方法interp1,因此您也可以简单地忽略该参数并使用命令:

interp1(TMP.time_hor, TMP.lane_hor, TMP.travel_time)

我希望这有帮助!

编辑:我刚刚意识到你要问的是你想使用 Python 中的“下一个”方法进行插值。这是我的做法:

import numpy as np
import scipy as sp

# Generate data
x = np.linspace(0, 1, 10)
y = np.exp(x)

# Create interpolation function 
f = sp.interpolate.interp1d(x, y, 'next')

# Create resampled range
x_resampled = np.linspace(x[0], x[-1], 100)

# Here's your interpolated data
y_interpolated = f(x_resampled)

推荐阅读