Numpy的meshgrid对于将两个向量转换为坐标网格非常有用.将此扩展到三维的最简单方法是什么?因此,给定三个向量x,y和z,构造可用作坐标的3x3D阵列(而不是2x2D阵列).
Numpy(我认为是1.8)现在支持使用meshgrid生成2D生成位置网格.一个重要的除了这真的帮了我是选择了索引的顺序(无论是能力xy
还是ij
分别笛卡尔或矩阵索引),我用下面的例子证明:
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_)
这是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)
你能告诉我们你是如何使用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]
例如.