python - matlab cumtrapz 和 scipy.integrate cumtrapz 的不同结果

标签 python matlab numpy scipy

我将一些 matlab 代码转换为 python 代码并调试这两个代码,我通过调用 cumtrapz 函数得到了不同的结果,我还验证了两者的输入数据是相似的。这是代码:

Python 代码

from numpy import zeros, ceil, array, mean, ptp, abs, sqrt, power
from scipy.integrate import cumtrapz

def step_length_vector(ics_y, fcs_y, acc_y, l, sf):
    step_length_m1 = zeros(int(ceil(len(ics_y)/2))-1) 

    for i in range(0, len(ics_y)-2, 2):
        av = acc_y[int(ics_y[i]):int(ics_y[i+2])+1]
        t = array(range(1, int((ics_y[i+2]-ics_y[i])+2)))/sf
        hvel = cumtrapz(t, av - mean(av), initial=0)
        h = cumtrapz(t, hvel - mean(hvel), initial=0)
        hend = ptp(h)
        sl = 6.8*(sqrt(abs(2*l*hend - hend**2)))
        step_length_m1[int(ceil(i/2))] = sl

    return step_length_m1

Matlab代码

function [StepLengthM1] = StepLengthVector(ICsY,FCsY,ACCY,l,sf)

        StepLengthM1 = zeros(1,ceil(length(ICsY)/2)-1);

        for i= 1:2:length(ICsY)-2
           av   = ACCY(ICsY(i):ICsY(i+2));           
           t    = (1:(ICsY(i+2)-ICsY(i))+1)/sf;
           hvel = cumtrapz(t,av-mean(av));      
           h    = cumtrapz(t,hvel-mean(hvel));
           hend = peak2peak(h);
           sl   = 6.8*(sqrt(abs(2*l*hend - hend.^2)));
           StepLengthM1(ceil(i/2)) = sl;
        end   
end

两个代码的 hvel 变量是不同的。也许我使用了错误的 scipy cumtrapz 因为我假设接收的 initial 值为 0。在这两种情况下,输入 ics_y(ICsy)fcs_y(FCsY)、acc_y(ACCY) 都是一维数组,并且 lsf 是标量。

谢谢!!!

最佳答案

(如果这个问题是关于 cumtrapz 的,您应该将测试简化为在 matlab 和 Python 中使用相同的输入数组对 cumtrapz 进行一次调用。另外,确保您仔细阅读每个函数的 matlab 和 SciPy 文档。SciPy 函数通常不是相应 matlab 函数的精确重复。)

问题是,当您同时给出 xy 值时,它们在 matlab/octave 中给出的顺序是 x, y code>,但在 SciPy 版本中,它是 y, x

例如,

octave:11> t = [0 1 1.5 4 4.5 6]
t =

   0.00000   1.00000   1.50000   4.00000   4.50000   6.00000

octave:12> y = [1 2 3 -2 0 1]
y =

   1   2   3  -2   0   1

octave:13> cumtrapz(t, y)
ans =

   0.00000   1.50000   2.75000   4.00000   3.50000   4.25000

scipy.integrate.cumtrapz 获得相同的结果:

In [22]: from scipy.integrate import cumtrapz                                                         

In [23]: t = np.array([0, 1, 1.5, 4, 4.5, 6])                                                         

In [24]: y = np.array([1, 2, 3, -2, 0, 1])                                                            

In [25]: cumtrapz(y, t, initial=0)                                                                    
Out[25]: array([0.  , 1.5 , 2.75, 4.  , 3.5 , 4.25])

关于python - matlab cumtrapz 和 scipy.integrate cumtrapz 的不同结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56974699/

相关文章:

Python Scipy Anneal 寻找超出范围的解决方案

matlab - 使用 Matlab 2014b 的锯齿状轮廓

matlab - Kmeans在matlab中绘图

python - 检查 numpy 数组是否具有正常形状

python - 安装pygame时出错

python - 在类中声明装饰器

matlab - 向量化 Matlab 中一维向量范围的选择

python - n维数组中唯一值的索引

python - 列表到混合维度矩阵

java - 从 Java 调用 Python 脚本。我应该使用 Docker 吗?