我试图了解网格网格如何索引输出相对于输入的维度。我注意到它总是会转置前两个维度。例如,当提供长度为 7 的 x 和长度为 6 的 y 时,它将返回输出数组作为 6x7 数组,而不是 7x6 数组。
这显然是设计使然,所以我试图理解原因/逻辑,以便我可以按预期使用它。有人可以阐明这一点吗?谢谢!
import numpy as np
#specify input dimensions of different lengths to aid in identifying which output index a dimension belongs to
x = np.linspace(0,60,7)
y = np.linspace(0,50,6)
z = np.linspace(0,40,5)
i = np.linspace(0,30,4)
j = np.linspace(0,20,3)
#2D mesh grid, output dimensions transposed from input
xx, yy = np.meshgrid(x,y)
print(xx.shape)
print(yy.shape)
#3D mesh grid, first two output dimensions transposed from input
xx, yy, zz = np.meshgrid(x,y,z)
print(xx.shape)
print(yy.shape)
print(zz.shape)
#4D meshgrid, first two output dimensions transposed from input, rest are in input order
xx, yy, zz, ii = np.meshgrid(x,y,z,i)
print(xx.shape)
print(yy.shape)
print(zz.shape)
print(ii.shape)
#5D meshgrid, first two output dimensions transposed from input, rest are in input order
xx, yy, zz, ii, jj = np.meshgrid(x,y,z,i,j)
print(xx.shape)
print(yy.shape)
print(zz.shape)
print(ii.shape)
print(jj.shape)
Run Code Online (Sandbox Code Playgroud)
可以通过将“indexing”选项设置为“ij”来完成此操作。该功能是在 numpy 1.7.0 版本中添加的。 https://docs.scipy.org/doc/numpy/reference/ generated/numpy.meshgrid.html
import numpy as np
#specify input dimensions of different lengths to aid in identifying which index dimension belongs to in output
x = np.linspace(0,60,7)
y = np.linspace(0,50,6)
z = np.linspace(0,40,5)
i = np.linspace(0,30,4)
j = np.linspace(0,20,3)
#2D mesh grid, output dimensions transposed from input
xx, yy = np.meshgrid(x,y,indexing='ij')
print(xx.shape)
print(yy.shape)
#3D mesh grid, first two output dimensions transposed from input
xx, yy, zz = np.meshgrid(x,y,z,indexing='ij')
print(xx.shape)
print(yy.shape)
print(zz.shape)
#4D meshgrid, first two output dimensions transposed from input, rest are in input order
xx, yy, zz, ii = np.meshgrid(x,y,z,i,indexing='ij')
print(xx.shape)
print(yy.shape)
print(zz.shape)
print(ii.shape)
#5D meshgrid, first two output dimensions transposed from input, rest are in input order
xx, yy, zz, ii, jj = np.meshgrid(x,y,z,i,j,indexing='ij')
print(xx.shape)
print(yy.shape)
print(zz.shape)
print(ii.shape)
print(jj.shape)
Run Code Online (Sandbox Code Playgroud)
我认为这就是轴坐标和矩阵坐标之间的区别。当您考虑参考系中的一组轴时,首先提到 x,然后才提到 y 是有意义的。例如,我们都被教导过 y = f(x)。然而,就矩阵而言,我们知道我们需要首先按行索引:(0, 1) 是第二列的第一个元素。现在,如果您尝试在图形上表示矩阵,则会出现问题,因为 x 轴对应于列,y 轴对应于行:存在不匹配。因此,如果您要获取 (7, 6) 数组并将其粘贴到图形上,则坐标将不匹配,因为列值将是 y 坐标。我相信,这就是为什么需要转置操作,以在矩阵表示和轴坐标之间保持一致。
归档时间: |
|
查看次数: |
2996 次 |
最近记录: |