ENH: equivalent to MATLAB's colon operator
See original GitHub issueComing to Python/NumPy from Matlab, I’m missing something like Matlab’s three-argument colon-operator:
>> 0:0.1:1
ans =
Columns 1 through 3
0 0.1 0.2
Columns 4 through 6
0.3 0.4 0.5
Columns 7 through 9
0.6 0.7 0.8
Columns 10 through 11
0.9 1
In Matlab, I used this operator routinely. It is especially useful when creating a range of values for plotting a function, e.g. x = -1:0.1:1; plot(x, x.^2)
.
NumPy’s alternatives for this are linspace
and arange
. However, the former makes it hard to hit specific values (in the plotting example, I have to figure out that there are 21 values), and the latter excludes the stop value. I get that arange
follows the behavior of range
, but for the mentioned application which has nothing to do with indexing it is just impractical.
I also understand that a naive implementation of the colon operator runs into floating point problems. However, in many years of using Matlab I never ran into a situation where it didn’t do the expected thing. I now managed to find an archived blog post that explains part of their implementation, with an attached complete implementation. I tested it, and as far as I can see it does exactly what the colon operator does.
Would you be open to including an implementation of this algorithm in NumPy? It could be called colon
to make it easy for people switching, or irange
where the i
stands for “inclusive”. For example with a signature irange(start, stop, step=1)
.
Issue Analytics
- State:
- Created 3 years ago
- Comments:11 (7 by maintainers)
I think we need to at spend some effort collecting together old bug reports on this, because we keep repeating ourselves in addressing them.
@allefeld, I think a lot of the responses you got here ended up being about the syntactic sugar of the matlab
:
operator, when really all you cared about was the behavior of the functioncolon(a, b, c)
. Sorry about that.Yes, exactly.