3D中的Numpy meshgrid

时间:2009-12-01 16:53:38

标签: python numpy

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

7 个答案:

答案 0 :(得分:40)

Numpy(我认为是1.8)现在支持使用meshgrid生成2D位置网格的更高版本。真正帮助我的一个重要补充是能够选择索引顺序(分别为xyij进行笛卡尔坐标或矩阵索引),我通过以下示例进行了验证:

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_)

答案 1 :(得分:29)

这是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)

答案 2 :(得分:7)

您能告诉我们您如何使用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

答案 3 :(得分:5)

我认为你想要的是

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

例如。

答案 4 :(得分:4)

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))'

答案 5 :(得分:4)

这是我写的网格网格的多维版本:

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

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

答案 6 :(得分:-1)

您可以通过更改顺序来实现:

import numpy as np
xx = np.array([1,2,3,4])
yy = np.array([5,6,7])
zz = np.array([9,10])
y, z, x = np.meshgrid(yy, zz, xx)