Skip to content
Advertisement

Convert array 1:n in matlab to python

I have question similar to this, and possibly a much simpler one:

We use the

k = 1:n;

a lot in Matlab. But in Python I simply struggle to get this simple thing work. I tried using arange, but never really realized what the error is:

>>> arange(1,]10[,1,])
File "<stdin>", line 1
arange(1,]10[,1,])
         ^
SyntaxError: invalid syntax
>>> arange(1,10[,1,])
  File "<stdin>", line 1
    arange(1,10[,1,])
                ^
SyntaxError: invalid syntax
>>> arange([1,]10[,1,])
  File "<stdin>", line 1
    arange([1,]10[,1,])
                ^
SyntaxError: invalid syntax
>>> np.arange
<built-in function arange>
>>> arange([1], 10[,1])
  File "<stdin>", line 1
    arange([1], 10[,1])
                   ^
SyntaxError: invalid syntax

I went to the numpy website and tried to give the syntax there, but again:

>>> import numpy as np
>>> np.arange([1],10[,1],dtype=None)
  File "<stdin>", line 1
    np.arange([1],10[,1],dtype=None)
                     ^
SyntaxError: invalid syntax

I wouldn’t have written this post just to clarify something of this sort, but my point is why is this simplest Matlab command so very complicated in Python? I even used this tool to convert .m codes to .py codes, with little effect.

EDIT after the post from @mskimm: Thanks! One related question. To write something very similar to the following in Matlab:

n = 100;
k = 1:n;
z = (n-k)./(n-k-1);
plot(k,log(z))

I ended up writing this in Python:

from __future__ import division
import numpy as np
import matplotlib.pyplot as plt

# test code to check the shape of a curve
n = 100
k = np.arange(1,n+1)
z = (n - k) / (n - k - 1)

fig = plt.figure()
ax = fig.gca()

plt.plot(k, np.log(z))
plt.show()

Is this the right way of doing it? Or there is a better way of doing the plot() ?

Advertisement

Answer

Welcome to Numpy!

1:n is the same as arange(1, n+1, 1) where the first 1 is start, n+1 is stop, and the last 1 is step. Note that Numpy index is started at 0 whereas Matlab is 1. So I think

np.arange(0, n, 1) # will generate 0, 1, ..., n-1

is more appropriate to array indexing.

[] means optional value. If you don’t give an explicit value, start is 0 and step is 1. You can use

np.arange(n) # will generate 0, 1, ..., n-1

This page helps Matlab users.

UPDATE

Comment for Matlab Users who start learning Numpy and is familiar with Matlab IDE.

I recommend to use Spyder or IPython Notebook.

Spyder IPython Notebook

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement