0

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?

2 Answers 2

6

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.