Does Python have a function like matlab's linspace
in its standard library?
If not, is there an easy way to implement it without installing an external package?
Here's a quick and easy definition of linspace in matlab terms.
Note
I don't need a "vector result" as defined by the link, a list will do fine.
linspace is an in-built function in Python's NumPy library. It is used to create an evenly spaced sequence in a specified interval.
The NumPy linspace function (sometimes called np. linspace) is a tool in Python for creating numeric sequences. It's somewhat similar to the NumPy arange function, in that it creates sequences of evenly spaced numbers structured as a NumPy array.
The numpy. linspace() function returns number spaces evenly w.r.t interval.
The linspace function generates linearly spaced vectors. It is similar to the colon operator ":", but gives direct control over the number of points. y = linspace(a,b) generates a row vector y of 100 points linearly spaced between and including a and b.
No, it doesn't. You can write your own (whicn isn't difficult), but if you are using Python to fulfil some of matlab's functionality then you definitely want to install numpy
, which has numpy.linspace
.
You may find NumPy for Matlab users informative.
The easiest way to implement this is a generator function:
from __future__ import division
def linspace(start, stop, n):
if n == 1:
yield stop
return
h = (stop - start) / (n - 1)
for i in range(n):
yield start + h * i
Example usage:
>>> list(linspace(1, 3, 5))
[1.0, 1.5, 2.0, 2.5, 3.0]
That said, you should definitely consider using NumPy, which provides the numpy.linspace()
function and lots of other features to conveniently work with numerical arrays.
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