Python索引问题(转换MATLAB代码)

Med*_*ata 0 python numpy

我正在尝试将一段Matlab代码转换为Python并遇到问题.

t = linspace(0,1,256);
s = sin(2*pi*(2*t+5*t.^2));
h = conj(s(length(s):-1:1));
Run Code Online (Sandbox Code Playgroud)

以上行h是为了计算脉冲响应,但是我的Python代码:

import numpy as np

t = np.linspace(0,1,256)
s = np.sin(2*np.pi*(2*t+5*t**2))

h = np.conj(s[len(s),-1,1])
Run Code Online (Sandbox Code Playgroud)

给了我一个错误IndexError: index 256 is out of bounds for axis 0 with size 256.我知道这与索引s数组有关,但我该如何解决呢?

nne*_*neo 6

请记住,Python是零索引的,而MATLAB是1索引的.另请注意,MATLAB切片表示法包括端点,而Python切片表示法则排除端点.

s(length(s):-1:1)是用于反转向量的常用MATLAB习惯用法.Python实际上有一个更好的语法:s[::-1].直接翻译将是s[len(s)-1:-1:-1].

另请注意,MATLAB start:step:stop对应于Python start:stop:step; step论证的立场是不同的.