3D的Numpy meshgrid

Numpy的meshgrid对于将两个向量转换为坐标网格非常有用。 将这个扩展到三个维度的最简单方法是什么? 因此,给定三个向量x,y和z,构造可用作坐标的3x3D数组(而不是2x2D数组)。

这里是meshgrid的源代码:

def meshgrid(x,y): """ Return coordinate matrices from two coordinate vectors. Parameters ---------- x, y : ndarray Two 1-D arrays representing the x and y coordinates of a grid. Returns ------- X, Y : ndarray For vectors `x`, `y` with lengths ``Nx=len(x)`` and ``Ny=len(y)``, return `X`, `Y` where `X` and `Y` are ``(Ny, Nx)`` shaped arrays with the elements of `x` and y repeated to fill the matrix along the first dimension for `x`, the second for `y`. See Also -------- index_tricks.mgrid : Construct a multi-dimensional "meshgrid" using indexing notation. index_tricks.ogrid : Construct an open multi-dimensional "meshgrid" using indexing notation. Examples -------- >>> X, Y = np.meshgrid([1,2,3], [4,5,6,7]) >>> X array([[1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3]]) >>> Y array([[4, 4, 4], [5, 5, 5], [6, 6, 6], [7, 7, 7]]) `meshgrid` is very useful to evaluate functions on a grid. >>> x = np.arange(-5, 5, 0.1) >>> y = np.arange(-5, 5, 0.1) >>> xx, yy = np.meshgrid(x, y) >>> z = np.sin(xx**2+yy**2)/(xx**2+yy**2) """ x = asarray(x) y = asarray(y) numRows, numCols = len(y), len(x) # yes, reversed x = x.reshape(1,numCols) X = x.repeat(numRows, axis=0) y = y.reshape(numRows,1) Y = y.repeat(numCols, axis=1) return X, Y 

理解起来相当简单。 我把这个模式扩展到任意数量的维度,但是这个代码并没有被优化(也没有彻底的错误检查),但是你得到了你所支付的。 希望它有助于:

 def meshgrid2(*arrs): arrs = tuple(reversed(arrs)) #edit lens = map(len, arrs) dim = len(arrs) sz = 1 for s in lens: sz*=s ans = [] for i, arr in enumerate(arrs): slc = [1]*dim slc[i] = lens[i] arr2 = asarray(arr).reshape(slc) for j, sz in enumerate(lens): if j!=i: arr2 = arr2.repeat(sz, axis=j) ans.append(arr2) return tuple(ans) 

Numpy(截至1.8我认为)现在支持更高的2D网格与位置网格。 一个重要的添加,帮助我的是能够select索引顺序( xyij分别为笛卡尔或matrix索引),我用下面的例子validation:

 import numpy as np x_ = np.linspace(0., 1., 10) y_ = np.linspace(1., 2., 20) z_ = np.linspace(3., 4., 30) x, y, z = np.meshgrid(x_, y_, z_, indexing='ij') assert np.all(x[:,0,0] == x_) assert np.all(y[0,:,0] == y_) assert np.all(z[0,0,:] == z_) 

你能告诉我们你是如何使用np.meshgrid? 有一个很好的机会,你真的不需要meshgrid,因为numpy广播可以做同样的事情,而不会产生重复的数组。

例如,

 import numpy as np x=np.arange(2) y=np.arange(3) [X,Y] = np.meshgrid(x,y) S=X+Y print(S.shape) # (3, 2) # Note that meshgrid associates y with the 0-axis, and x with the 1-axis. print(S) # [[0 1] # [1 2] # [2 3]] s=np.empty((3,2)) print(s.shape) # (3, 2) # x.shape is (2,). # y.shape is (3,). # x's shape is broadcasted to (3,2) # y varies along the 0-axis, so to get its shape broadcasted, we first upgrade it to # have shape (3,1), using np.newaxis. Arrays of shape (3,1) can be broadcasted to # arrays of shape (3,2). s=x+y[:,np.newaxis] print(s) # [[0 1] # [1 2] # [2 3]] 

问题是S=X+Y可以并且应该被s=x+y[:,np.newaxis]代替,因为后者不需要(可能是大的)重复数组。 它也容易推广到更高的尺寸(更多的轴)。 如果需要,您只需在必要时添加np.newaxis来实现广播。

有关numpy广播的更多信息,请参阅http://www.scipy.org/EricsBroadcastingDoc

我想你想要的是

 X, Y, Z = numpy.mgrid[-10:10:100j, -10:10:100j, -10:10:100j] 

例如。

这是我写的一个多维版本的meshgrid:

 def ndmesh(*args): args = map(np.asarray,args) return np.broadcast_arrays(*[x[(slice(None),)+(None,)*i] for i, x in enumerate(args)]) 

请注意,返回的数组是原始数组数据的视图,因此更改原始数组将影响坐标数组。

numpy.ix_不应该写一个新的函数, 而应该做你想要的。

以下是文档中的一个示例:

 >>> ixgrid = np.ix_([0,1], [2,4]) >>> ixgrid (array([[0], [1]]), array([[2, 4]])) >>> ixgrid[0].shape, ixgrid[1].shape ((2, 1), (1, 2))'