I want to create an array which represent X-Y panel (-50, 50). That is:
[[-50, -50], [-49,-50],[-48,-50]....[50,50]]
, which is at length 101*101.
Clearly, I can generate through a double loop from (-50,50)
. I'm wondering the prefered
way of doing this?
Create a NumPy array from an object implementing the __dlpack__ protocol. Construct an array from data in a text or binary file. Construct an array by executing a function over each coordinate. Create a new 1-dimensional array from an iterable object.
meshgrid function is used to create a rectangular grid out of two given one-dimensional arrays representing the Cartesian indexing or Matrix indexing. Meshgrid function is somewhat inspired from MATLAB. Consider the above figure with X-axis ranging from -4 to 4 and Y-axis ranging from -5 to 5.
numpy.meshgrid
is obviously the clearest way to me (as @benbo has mentioned), you need one more step to ravel
or flatten
the 2D grid array:
In [131]: import numpy as np
...: x=np.linspace(-2, 2, 5)
...: y=np.linspace(-2, 2, 5)
...: xx,yy=np.meshgrid(x,y)
...: coords=np.array((xx.ravel(), yy.ravel())).T
In [132]: coords
Out[132]:
array([[-2., -2.],
[-1., -2.],
[ 0., -2.],
[ 1., -2.],
[ 2., -2.],
[-2., -1.],
......
[ 1., 2.],
[ 2., 2.]])
In [133]:
Or as @John mentioned, shorten your code with np.c_
to skip the transpose:
coords=np.c_[xx.ravel(), yy.ravel()]
To benchmark:
In [156]: %timeit coords=np.array((xx.ravel(), yy.ravel())).T
100000 loops, best of 3: 14.6 µs per loop
In [157]: %timeit coords=np.c_[xx.ravel(), yy.ravel()] #not as efficient as ↑
10000 loops, best of 3: 47.6 µs per loop
How about this:
In [15]: import numpy as np
In [16]: a = np.arange(-3,4)
In [17]: a1 = np.tile(a, (7,1))
In [18]: np.dstack((a1, a1.T)).reshape(-1, 2)
Result:
array([[-3, -3],
[-2, -3],
[-1, -3],
[ 0, -3],
[ 1, -3],
....
[-1, 3],
[ 0, 3],
[ 1, 3],
[ 2, 3],
[ 3, 3]])
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