I would like a list of 2d NumPy arrays (x,y) , where each x is in {-5, -4.5, -4, -3.5, ..., 3.5, 4, 4.5, 5} and the same for y.
I could do
x = np.arange(-5, 5.1, 0.5) y = np.arange(-5, 5.1, 0.5)
and then iterate through all possible pairs, but I'm sure there's a nicer way...
I would like something back that looks like:
[[-5, -5], [-5, -4.5], [-5, -4], ... [5, 5]]
but the order does not matter.
arange function. The essential difference between NumPy linspace and NumPy arange is that linspace enables you to control the precise end value, whereas arange gives you more direct control over the increments between values in the sequence.
linspace is an in-built function in Python's NumPy library. It is used to create an evenly spaced sequence in a specified interval.
In general numpy arrays can have more than one dimension. One way to create such array is to start with a 1-dimensional array and use the numpy reshape() function that rearranges elements of that array into a new shape.
linspace. Return evenly spaced numbers over a specified interval. Returns num evenly spaced samples, calculated over the interval [start, stop].
You can use np.mgrid
for this, it's often more convenient than np.meshgrid
because it creates the arrays in one step:
import numpy as np X,Y = np.mgrid[-5:5.1:0.5, -5:5.1:0.5]
For linspace-like functionality, replace the step (i.e. 0.5
) with a complex number whose magnitude specifies the number of points you want in the series. Using this syntax, the same arrays as above are specified as:
X, Y = np.mgrid[-5:5:21j, -5:5:21j]
You can then create your pairs as:
xy = np.vstack((X.flatten(), Y.flatten())).T
As @ali_m suggested, this can all be done in one line:
xy = np.mgrid[-5:5.1:0.5, -5:5.1:0.5].reshape(2,-1).T
Best of luck!
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