python - 为什么 Matlab interp1 产生的结果与 numpy interp 不同?
问题描述
编辑:编辑代码以产生与 Matlab 一致的结果。见下文。
我正在将 Matlab 脚本转换为 Python,并且在某些情况下线性插值结果不同。我想知道为什么以及是否有任何方法可以解决这个问题?
这是 Matlab 和 Python 中的代码示例以及结果输出(请注意,在这种情况下 t 恰好等于 tin):
MATLAB:
t= [ 736696., 736696.00208333, 736696.00416667, 736696.00625, 736696.00833333, 736696.01041667, 736696.0125];
tin =[ 736696., 736696.00208333, 736696.00416667, 736696.00625, 736696.00833333, 736696.01041667, 736696.0125];
xin = [ nan , 1392., 1406. , 1418. , nan , 1442. , nan];
interp1(tin,xin,t)
ans =
NaN 1392 1406 1418 NaN 1442 NaN
Python(numpy):
(scipy interpolate.interp1d 产生与 numpy 相同的结果)
t= [ 736696., 736696.00208333, 736696.00416667, 736696.00625, 736696.00833333, 736696.01041667, 736696.0125];
tin =[ 736696., 736696.00208333, 736696.00416667, 736696.00625, 736696.00833333, 736696.01041667, 736696.0125];
xin = [ nan , 1392., 1406. , 1418. , nan , 1442. , nan];
x = np.interp(t,tin,xin)
array([ nan, 1392., 1406., nan, nan, nan, nan])
# Edit
# Find indices where t == tin and if the np.interp output
# does not match the xin array, overwrite the np.interp output at those
# indices
same = np.where(t == tin)[0]
not_same = np.where(xin[same] != x[same])[0]
x[not_same] = xin[not_same]
解决方案
似乎 Matlab 在其插值中包含一个额外的相等检查。
线性一维插值通常通过找到两个跨越输入值的 x 值来完成x
,然后将结果计算为:
y = y1 + (y2-y1)*(x-x1)/(x2-x1)
如果您传入一个与输入 x 坐标之一完全x
相等的值,则例程通常会计算正确的值,因为它将为零。但是,如果您的输入数组具有as或这些将传播到结果。x-x1
nan
y1
y2
根据您发布的代码,我最好的猜测是 Matlab 的插值函数有一个额外的检查,类似于:
if x == x1:
return y1
并且 numpy 函数没有这个检查。
要在 numpy 中实现相同的效果,您可以执行以下操作:
np.where(t == tin,xin,np.interp(t,tin,xin))
推荐阅读
- reactjs - 是否可以在 React 的静态 getDerivedStateFromPRops 方法中使用 ClearInterval?
- javascript - 在js中的静态函数中将对象作为参数传递
- reactjs - 从反应应用程序读取 kubernetes pod 的 configmap 中设置的环境变量?
- powershell - GCP API - tagamanger REST API - powershell - 域验证
- android - 活动无法从广播接收器开始
- jquery - 如何制作像输入类型单选按钮一样工作的 div html 标签?
- python - Scrapy - 从 javascript 脚本响应中检索身份验证令牌
- ios - 你如何对 UICollectionView 单元格性能进行基准测试?
- google-app-engine - 第一个数据存储区查询总是很慢
- extjs - Extjs Grid在childlongpress后防止childtap