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]
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 .
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
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With