如何将meshgrid的输出转换为对应的点数组? [英] How to convert the output of meshgrid to the corresponding array of points?
问题描述
我想创建一个与网格相对应的点列表.因此,如果我想创建从 (0, 0)
到 (1, 1)
的区域网格,它将包含点 (0, 0)
、(0, 1)
、(1, 0)
和 (1, 0)
.
I want to create a list of points that would correspond to a grid. So if I want to create a grid of the region from (0, 0)
to (1, 1)
, it would contain the points (0, 0)
, (0, 1)
, (1, 0)
and (1, 0)
.
我知道这可以通过以下代码完成:
I know that that this can be done with the following code:
g = np.meshgrid([0,1],[0,1])
np.append(g[0].reshape(-1,1),g[1].reshape(-1,1),axis=1)
产生结果:
array([[0, 0],
[1, 0],
[0, 1],
[1, 1]])
我的问题有两个:
- 有没有更好的方法来做到这一点?
- 有没有办法将其推广到更高维度?
推荐答案
我刚刚注意到 numpy 中的文档提供了一种更快的方法来做到这一点:
I just noticed that the documentation in numpy provides an even faster way to do this:
X, Y = np.mgrid[xmin:xmax:100j, ymin:ymax:100j]
positions = np.vstack([X.ravel(), Y.ravel()])
使用链接的 meshgrid2 函数并将ravel"映射到生成的网格,可以轻松地将其推广到更多维度.
This can easily be generalized to more dimensions using the linked meshgrid2 function and mapping 'ravel' to the resulting grid.
g = meshgrid2(x, y, z)
positions = np.vstack(map(np.ravel, g))
对于每个轴上有 1000 个刻度的 3D 数组,结果比 zip 方法快 35 倍.
The result is about 35 times faster than the zip method for a 3D array with 1000 ticks on each axis.
要比较这两种方法,请考虑以下代码段:
To compare the two methods consider the following sections of code:
创建有助于创建网格的众所周知的刻度线.
Create the proverbial tick marks that will help to create the grid.
In [23]: import numpy as np
In [34]: from numpy import asarray
In [35]: x = np.random.rand(100,1)
In [36]: y = np.random.rand(100,1)
In [37]: z = np.random.rand(100,1)
为网格定义 mgilson 链接到的函数:
Define the function that mgilson linked to for the meshgrid:
In [38]: def meshgrid2(*arrs):
....: arrs = tuple(reversed(arrs))
....: 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)
创建网格和计时这两个函数.
Create the grid and time the two functions.
In [39]: g = meshgrid2(x, y, z)
In [40]: %timeit pos = np.vstack(map(np.ravel, g)).T
100 loops, best of 3: 7.26 ms per loop
In [41]: %timeit zip(*(x.flat for x in g))
1 loops, best of 3: 264 ms per loop
这篇关于如何将meshgrid的输出转换为对应的点数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!