Reputation: 935
Is there an equivalent MATLAB function for the range()
function in Python?
I'd really like to be able to type something like range(-10, 11, 5)
and get back [-10, -5, 0, 5, 10]
instead of having to write out the entire range by hand.
Upvotes: 13
Views: 31909
Reputation: 12345
There are two relevant functions. The colon :
operator, you can use the linspace
function. The best function to use depends on what you want to specify.
Examples:
x = -10:5:10; % Count by 5's from -10 to 10. (or "colon(-10, 5, 10)")
x = linspace(-10, 10, 5); % 5 even increments between -10 and 10
The result of the colon
operator will always include the first argument and the desired spacing, but generally will not include the last argument. (e.g. x = -10:5:11
).
The linspace
function will always include the desired first and last elements, but will the element spacing will vary. (e.g. linspace(-10, 11, 5)
).
Upvotes: 8
Reputation: 124563
Others have mentioned the colon
operator. You just have to be aware of some differences.
In Python, range
takes all integer parameters and returns an integer list. In MATLAB, the colon operator can handle floating point in both the start/stop as well as the step size.
I would say that numpy.arange
is a closer match to MATLAB's colon operator.
Upvotes: 3
Reputation: 20309
Yes, there is the :
operator. The command -10:5:11
would produce the vector [-10, -5, 0, 5, 10];
Upvotes: 18