行是网格点坐标的矩阵

Matrix in which rows are coordinates of points of a meshgrid

this tutorial 中,我发现类似

的代码
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)

有没有比使用 meshgrid+vstack+ravel 更短的方法来获取行是网格点坐标的矩阵+transpose?

输出:

[[-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]
 ...

你可以跳过meshgrid,直接拿xcartesian producty:

就可以更直接的得到你想要的
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)

输出:

[[-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]
...
]

这里是 repeat 和 tile 方法的实现。

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)

我想 meshgrid 方法使用相同的方法来填充它的结果矩阵。

这是使用 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)