Reputation: 46371
In this tutorial I find code like
import numpy as np
x = np.linspace(-5, 5, 20)
y = np.linspace(-1, 1, 10)
Y, X = np.meshgrid(y, x)
xy = np.vstack([X.ravel(), Y.ravel()]).T
print(xy)
Isn't there a shorter way to get a matrix where rows are coordinates of points of the meshgrid, than using meshgrid
+vstack
+ravel
+transpose
?
Output:
[[-5. -1. ]
[-5. -0.77777778]
[-5. -0.55555556]
[-5. -0.33333333]
[-5. -0.11111111]
[-5. 0.11111111]
[-5. 0.33333333]
[-5. 0.55555556]
[-5. 0.77777778]
[-5. 1. ]
[-4.47368421 -1. ]
[-4.47368421 -0.77777778]
...
Upvotes: 0
Views: 328
Reputation: 1017
Here is a one-liner using meshgrid
:
import numpy as np
x = np.linspace(-5, 5, 20)
y = np.linspace(-1, 1, 10)
xy = np.stack(np.meshgrid(x, y, indexing='ij'), -1).reshape(-1, 2)
print(xy)
Upvotes: 1
Reputation: 5448
Here is implementation with repeat and tile methods.
import numpy as np
x = np.linspace(-5, 5, 20)
y = np.linspace(-1, 1, 10)
xy = np.empty((len(x) * len(y), 2))
xy[:, 0] = np.repeat(x, len(y))
xy[:, 1] = np.tile(y, len(x))
print(xy)
I suppose meshgrid method uses same approach to fill it's result matrix.
Upvotes: 1
Reputation: 13999
You can skip meshgrid
and get what you want more directly by just taking the cartesian product of x
and y
:
from itertools import product
import numpy as np
x = np.linspace(-5, 5, 20)
y = np.linspace(-1, 1, 10)
xy = np.array(list(product(x,y)))
print(xy)
Output:
[[-5. -1. ]
[-5. -0.77777778]
[-5. -0.55555556]
[-5. -0.33333333]
[-5. -0.11111111]
[-5. 0.11111111]
[-5. 0.33333333]
[-5. 0.55555556]
[-5. 0.77777778]
[-5. 1. ]
[-4.47368421 -1. ]
[-4.47368421 -0.77777778]
[-4.47368421 -0.55555556]
[-4.47368421 -0.33333333]
...
]
Upvotes: 2