Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create range of numbers in Python like in MATLAB

Is there any way to create a range of numbers in Python like MATLAB using a simple syntax, i.e, not using loops. For example:

MATLAB: a = 1:0.5:10 give a = [1 1.5 2 2.5 3 3.5 .... 9.5 10]

like image 701
efirvida Avatar asked Jun 30 '15 16:06

efirvida


People also ask

How do you create a range of numbers in Matlab?

y = range( X , dim ) returns the range along the operating dimension dim of X . For example, if X is a matrix, then range(X,2) is a column vector containing the range value of each row. y = range( X , vecdim ) returns the range over the dimensions specified in the vector vecdim .


2 Answers

As others have pointed out, np.arange gets you closest to what you are used to from matlab. However, np.arange excludes the end point. The solution that you proposed in your own answer can lead to wrong results (see my comment).

This however, will always work:

start = 0
stop = 3
step = 0.5
a = np.arange(start, stop+step, step)

For further reading: Especially if you are an experienced matlab-user, this guide/cheat sheet might be interesting: http://wiki.scipy.org/NumPy_for_Matlab_Users

like image 97
hitzg Avatar answered Sep 19 '22 20:09

hitzg


Numpy has arange and r_ which look something like this:

import numpy as np
print(np.arange(1, 3, .5))
# [ 1.   1.5  2.   2.5]
print(np.r_[1:3:.5])
# [ 1.   1.5  2.   2.5]

Notice that it is a little different than matlab, first the order of the stop and step are reversed in numpy compared to matlab, and second the stop is not included the the result. You might also consider using linspace it's often preferred over arange when you're working with floating point numbers because num can be defined more precisely than step:

print(np.linspace(1, 3, num=5))
# [ 1.   1.5  2.   2.5  3. ]

or

print(np.linspace(1, 3, num=4, endpoint=False))
# [ 1.   1.5  2.   2.5]
like image 38
Bi Rico Avatar answered Sep 20 '22 20:09

Bi Rico