首页 > 解决方案 > 矩阵,其中行是网格网格点的坐标

问题描述

本教程中,我找到了类似的代码

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

标签: pythonarraysnumpymesh

解决方案


您可以通过使用and的笛卡尔积来更直接地跳过meshgrid并获得您想要的内容:xy

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

推荐阅读