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

时间:2014-06-24 01:38:37

标签: 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));

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])

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

2 个答案:

答案 0 :(得分: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参数的位置不同。

答案 1 :(得分:1)

python这样做的方法更简单:

In [242]:

a=np.arange(10)
print a
print a[::-1]
[0 1 2 3 4 5 6 7 8 9]
[9 8 7 6 5 4 3 2 1 0]

简单地说:s[::-1]

这是在python 2.3

中首次引入的
相关问题