Reputation: 3961
I'm trying to convert a piece of Matlab code into Python and am running into a problem.
t = linspace(0,1,256);
s = sin(2*pi*(2*t+5*t.^2));
h = conj(s(length(s):-1:1));
The above line for h
is meant to calculate the impulse response, but my Python code:
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])
gives me an error IndexError: index 256 is out of bounds for axis 0 with size 256
. I know that this has to do with indexing the s
array, but how can I fix it?
Upvotes: 0
Views: 176
Reputation: 179422
Remember that Python is zero-indexed, while MATLAB is 1-indexed. Note too that the MATLAB slice notation includes the endpoint, whereas the Python slice notation excludes the endpoint.
s(length(s):-1:1)
is a common MATLAB idiom for reversing a vector. Python actually has a nicer syntax: s[::-1]
. A direct translation would be s[len(s)-1:-1:-1]
.
Also note that MATLAB start:step:stop
corresponds to the Python start:stop:step
; the position of the step
argument is different.
Upvotes: 6
Reputation: 54340
The python
way to do it is even simpler:
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]
simply: s[::-1]
This was first introduced in python 2.3
Upvotes: 1