np.meshgrid()

1.meshgrid函数介绍

参数:
*xi,也就是x1,x2,…,xn :表示网格坐标的一维数组。
copy:默认为True,如果为False,就返回原始数组以节省内存。
sparse:默认值为False如果为True,则返回一个稀疏网格以节省内存。
indexing:输出的笛卡尔(默认为“ xy”)或矩阵(“ ij”)索引。(后面有例子介绍该参数)

return :返回网格坐标矩阵(返回值为list,list中包含各个方向的坐标矩阵)

看到这可能还不是很理解,举个例子就很明白了,如下图所示,下图二维平面中有6个网格坐标,可以看出他们的横坐标为[0, 1, 2],纵坐标为[0, 1],倘若只知道他们的横坐标和纵坐标的一维数组,怎么构建这6个网格坐标,meshgrid的作用就是这个。
在这里插入图片描述

>>> a = [0, 1, 2]
>>> b = [0, 1]
>>> np.meshgrid(a,b)
[array([[0, 1, 2],[0, 1, 2]]), array([[0, 0, 0],[1, 1, 1]])]
>>>

返回的结果现在还不是6个点的坐标,但是将a中的元素与b中的每个元素一一对应就得到了上述6个点的坐标。

那么indexing的作用是什么呢?

>>> np.meshgrid(a,b,indexing = 'ij')
[array([[0, 0], [1, 1],[2, 2]]), array([[0, 1],[0, 1], [0, 1]])]
>>>

也就是若indexing = ‘xy’,返回的矩阵形状为(N2, N1, N3,…Nn),其中Ni = len(xi)。若indexing = ‘ij’,则返回的矩阵形状为(N1, N2, N3,…Nn)。具体的影响就是处理数据时,读取数据方式不同。

 xv, yv = np.meshgrid(x, y, sparse=False, indexing='ij')
        for i in range(nx):
            for j in range(ny):
                # treat xv[i,j], yv[i,j]

        xv, yv = np.meshgrid(x, y, sparse=False, indexing='xy')
        for i in range(nx):
            for j in range(ny):
                # treat xv[j,i], yv[j,i]

sparse为True时,返回稀疏的网格(为了节省内存),也就是该坐标矩阵下的元素有哪些(由于每行/列下的元素都一样,所以返回一行或一列就可以知道该坐标矩阵下的元素)。

>>> x = np.meshgrid(a,b,sparse= True)
>>> x
[array([[0, 1, 2]]), array([[0],
       [1]])]
>>>

接下来把meshgrid的结果变为最终的坐标点

>>> a = [0, 1, 2]
>>> b = [0, 1]
>>> np.meshgrid(a,b)
[array([[0, 1, 2],[0, 1, 2]]), array([[0, 0, 0],[1, 1, 1]])]
>>> x, y = np.meshgrid(a,b)
>>> x.flatten()[:, np.newaxis]
array([[0],
       [1],
       [2],
       [0],
       [1],
       [2]])
>>> y.flatten()[:, np.newaxis]
array([[0],
       [0],
       [0],
       [1],
       [1],
       [1]])
>>> xx = x.flatten()[:, np.newaxis]
>>> yy = y.flatten()[:, np.newaxis]
>>> np.c_[xx, yy]
array([[0, 0],
       [1, 0],
       [2, 0],
       [0, 1],
       [1, 1],
       [2, 1]])
>>>

np.newaxis介绍:可以在数组索引中使用np.newaxis对象添加大小为1的新尺寸,如:

>>> a.shape
(5, 7)
>>> a[:,np.newaxis,:].shape
(5, 1, 7)

>>> x = np.arange(5)
>>> x[:, np.newaxis]
array([[0],
       [1],
       [2],
       [3],
       [4]])
>>>

np.flatten()介绍:
原型声明:def flatten(self, order='C'):

Parameters
order{‘C’, ‘F’, ‘A’, ‘K’}, optional
“ C”表示按行优先(C样式)的顺序展平。“ F”表示按列主(Fortran样式)的顺序展平。“ A”表示如果a在内存中是连续的,则按列优先顺序进行展平;否则,按行优先进行展平。“ K”表示按元素在内存中出现的顺序展平 。默认值为“ C”。
Returns
返回展平为一维的数组副本。


2.meshgrid函数官方说明

meshgrid的官方api

def meshgrid(*xi, copy=True, sparse=False, indexing='xy'):
    """
    Return coordinate matrices from coordinate vectors.

    Make N-D coordinate arrays for vectorized evaluations of
    N-D scalar/vector fields over N-D grids, given
    one-dimensional coordinate arrays x1, x2,..., xn.

    .. versionchanged:: 1.9
       1-D and 0-D cases are allowed.

    Parameters
    ----------
    x1, x2,..., xn : array_like
        1-D arrays representing the coordinates of a grid.
    indexing : {'xy', 'ij'}, optional
        Cartesian ('xy', default) or matrix ('ij') indexing of output.
        See Notes for more details.

        .. versionadded:: 1.7.0
    sparse : bool, optional
        If True a sparse grid is returned in order to conserve memory.
        Default is False.

        .. versionadded:: 1.7.0
    copy : bool, optional
        If False, a view into the original arrays are returned in order to
        conserve memory.  Default is True.  Please note that
        ``sparse=False, copy=False`` will likely return non-contiguous
        arrays.  Furthermore, more than one element of a broadcast array
        may refer to a single memory location.  If you need to write to the
        arrays, make copies first.

        .. versionadded:: 1.7.0

    Returns
    -------
    X1, X2,..., XN : ndarray
        For vectors `x1`, `x2`,..., 'xn' with lengths ``Ni=len(xi)`` ,
        return ``(N1, N2, N3,...Nn)`` shaped arrays if indexing='ij'
        or ``(N2, N1, N3,...Nn)`` shaped arrays if indexing='xy'
        with the elements of `xi` repeated to fill the matrix along
        the first dimension for `x1`, the second for `x2` and so on.

    Notes
    -----
    This function supports both indexing conventions through the indexing
    keyword argument.  Giving the string 'ij' returns a meshgrid with
    matrix indexing, while 'xy' returns a meshgrid with Cartesian indexing.
    In the 2-D case with inputs of length M and N, the outputs are of shape
    (N, M) for 'xy' indexing and (M, N) for 'ij' indexing.  In the 3-D case
    with inputs of length M, N and P, outputs are of shape (N, M, P) for
    'xy' indexing and (M, N, P) for 'ij' indexing.  The difference is
    illustrated by the following code snippet::

        xv, yv = np.meshgrid(x, y, sparse=False, indexing='ij')
        for i in range(nx):
            for j in range(ny):
                # treat xv[i,j], yv[i,j]

        xv, yv = np.meshgrid(x, y, sparse=False, indexing='xy')
        for i in range(nx):
            for j in range(ny):
                # treat xv[j,i], yv[j,i]

    In the 1-D and 0-D case, the indexing and sparse keywords have no effect.

    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
    --------
    >>> nx, ny = (3, 2)
    >>> x = np.linspace(0, 1, nx)
    >>> y = np.linspace(0, 1, ny)
    >>> xv, yv = np.meshgrid(x, y)
    >>> xv
    array([[0. , 0.5, 1. ],
           [0. , 0.5, 1. ]])
    >>> yv
    array([[0.,  0.,  0.],
           [1.,  1.,  1.]])
    >>> xv, yv = np.meshgrid(x, y, sparse=True)  # make sparse output arrays
    >>> xv
    array([[0. ,  0.5,  1. ]])
    >>> yv
    array([[0.],
           [1.]])

    `meshgrid` is very useful to evaluate functions on a grid.

    >>> import matplotlib.pyplot as plt
    >>> x = np.arange(-5, 5, 0.1)
    >>> y = np.arange(-5, 5, 0.1)
    >>> xx, yy = np.meshgrid(x, y, sparse=True)
    >>> z = np.sin(xx**2 + yy**2) / (xx**2 + yy**2)
    >>> h = plt.contourf(x,y,z)
    >>> plt.show()

    """
  • 11
    点赞
  • 68
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 3
    评论
np.meshgrid是一个函数,用于生成N维坐标数组,以便对N维网格上的N维标量/矢量场进行矢量化评估。它接受一维坐标数组x1、x2、...、xn作为参数,并返回一个N维数组,其中每个维度对应于相应的坐标数组。\[1\] 使用np.meshgrid可以方便地生成三维及以上维度的坐标。例如,可以使用np.linspace生成一维坐标数组x、y、z,然后使用np.meshgrid(x, y, z)生成三维坐标数组X、Y、Z。通过np.concatenate函数可以将X、Y、Z合并为一个坐标数组coors。\[3\] 另外,根据引用\[2\]的描述,无论如何修改np.meshgrid()中x、y、z的顺序,都无法实现对x、y、z中的值都实现从小到大的排列。如果需要实现这样的排列,可以考虑使用其他方法,如np.repeat()。\[2\] #### 引用[.reference_title] - *1* [np.meshgrid()函数](https://blog.csdn.net/BIT_HXZ/article/details/128106699)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* *3* [np.meshgrid()函数 以及 三维空间中的坐标位置生成 以及 numpy.repeat()函数介绍](https://blog.csdn.net/jiongta9473/article/details/125179947)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

爱学习的贝塔

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值