从meshgrid数据

时间:2015-07-07 17:47:42

标签: python numpy mesh

我有一个立方网格,如下图所示。

我想列出每个子立方体的顶点,所以我最终得到一个嵌套的子立方体列表及其相应的顶点列表。

我最初的尝试是使用发电机,

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

dims = [9,9,9]    
spacer = 3
subBoxCoords = np.array([(x, y, z) for x in range(0, dims[0], spacer) for y in range(0, dims[1], spacer) for z in range(0, dims[2], spacer)])
ax.scatter(subBoxCoords[:,0], subBoxCoords[:,1], subBoxCoords[:,2], c='k', marker='o')

ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
ax.set_zlabel('Z Label')

这确实给了我所需的形状,但是坐标的排序方式是子框的顶点提取不是直接的。另外,我想将其概括为任意维度的框,因此间隔中的硬编码不是解决方案。

那么,我想我会使用meshgrid

nx,ny, nz = (3,3,3)
x = np.linspace(0, 10, nx)
y = np.linspace(0, 10, ny)
z = np.linspace(0, 10, nz)
xv, yv, zv = np.meshgrid(x, y, z, indexing='xy')

ax.scatter(xv, yv, zv, c='g', marker='^')

这似乎是实现我想要的非常强大的方式,但我感到困惑。是否可以meshgrid的方式直接访问vertex(x,y,z)中的顶点?甚至是直接提取子立方体的方法?

在我看来,解决方案非常接近,但我无法掌握它!

Cubic grid

1 个答案:

答案 0 :(得分:2)

meshgrid可能就是您所需要的,但meshgrid返回的数组的形状让人感到困惑。 Meshgrid返回三个坐标数组,形状相同。每个xv, yv, zv的形状为(len(x), len(y), len(z))。因此,要在角落(0, 2, 1)处提取坐标,您需要编写xv[0, 2, 1], yv[0, 2, 1], zv[0, 2, 1]

要提取所有子立方体的“角”坐标,有助于观察到,由于meshgrid返回的数组按顺序排序,xv[:-1, :-1, :-1]仅返回x的坐标每个子立方体的左下角。同样,xv[1:, 1:, 1:]返回每个子多维数据集的最右上角。其他六个角由切片:-11:的其他六个组合给出(例如,xv[:-1, 1:, :-1]给出了最左上角。)

因此,遍历:-11:的所有八种组合,以获得所有len(x)-1 * len(y-1) * len(z-1)子多维数据集的八个角的x,y,z坐标的三个平行数组的八个并行数组。 (如果您需要将子多维数据集角坐标数组设置为特定的形状或轴顺序,或者如果要使用单个索引来指定子多维数据集而不是三个,请使用rollaxisswapaxis和{ {1}}根据需要。)

shape

enter image description here

总是有一种方法可以将索引转换为import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D import itertools nx, ny, nz = (3,3,3) x = np.linspace(0, 10, nx) y = np.linspace(0, 10, ny) z = np.linspace(0, 10, nz) xv, yv, zv = np.meshgrid(x, y, z, indexing='xy') slices = slice(None, -1), slice(1, None) cornerSlices = list(itertools.product(slices, slices, slices)) corners = np.array([(xv[s], yv[s], zv[s]) for s in cornerSlices]) # The shape of `corners` is `(len(cornerSlices), 3, len(x-1), len(y-1), len(z-1)` # The axes of `corners` represent, in the same order: the corner index; the cartesian # coordinate axis (the index into [x, y, z]); the x, y, and z indexes of the subcube. # Plot the first subcube (subcube 0, 0, 0) fig = plt.figure() ax = fig.add_subplot(111, projection='3d') subcube = corners[:, :, 0, 0, 0] subcubeX = subcube [:, 0] subcubeY = subcube [:, 1] subcubeZ = subcube [:, 2] ax.scatter(subcubeX , subcubeY , subcubeZ , c='g', marker='^') 而不是获取值,因为这些值在xv, yv, zv数组中重复了很多次。它将涉及将索引数组切割为corners而不是切片数组本身。我把头伸进ndarray伏都教后已经旋转了,所以我将把它当作练习。

相关问题