简体   繁体   English

如何迭代 MeshGrid?

[英]How can I iterate over a MeshGrid?

I have a function that returns the density estimate for points (x, y).我有一个 function 返回点 (x, y) 的密度估计。 I would like to iterate over all (x, y) points for a given 2-D grid and have the density function compute the estimate for each point so that I can have a matrix of density values which I can then plot.我想遍历给定二维网格的所有 (x, y) 点,并让密度 function 计算每个点的估计值,以便我可以有一个密度值矩阵,然后我可以使用 plot。

Say the function is called density(x, y) , that takes any point (x, y) and returns the density estimate (z) for that (x, y).假设 function 被称为density(x, y) ,它采用任意点 (x, y) 并返回该 (x, y) 的密度估计 (z)。 I would like to be able to apply the function to each point within a 2-Dimensional grid and store the density estimate wherein I could use, say, plt.pcolormesh() to view the density.我希望能够将 function 应用于二维网格中的每个点并存储密度估计值,其中我可以使用plt.pcolormesh()来查看密度。

How can I do this?我怎样才能做到这一点?

I think you want something on the lines of this.我想你想要一些关于这个的东西。

First, define a density function.首先,定义密度 function。 For simplicity, I am taking the function |x| + |y|为简单起见,我采用 function |x| + |y| |x| + |y| . .

def density(x, y):
    return np.abs(x) + np.abs(y)

Now let's define the points along x and y dimensions and populate the arrays.现在让我们定义沿xy维度的点并填充 arrays。 In the following example, x and y are 1D arrays which store n_x and n_y points each sampled uniformly in [-1, 1] .在以下示例中, xy是 1D arrays ,它们存储n_xn_y点,每个点均在[-1, 1]中均匀采样。

n_x = 100
n_y = 100
x = np.linspace(-1, 1, n_x)
y = np.linspace(-1, 1, n_y)

Compute the grid in terms of pairs of points and compute the density D over each point in the grid.根据点对计算网格并计算网格中每个点的密度D

xx, yy = np.meshgrid(x, y)
D = density(xx, yy)

Note that you don't need to explicitly iterate over meshgrid, you can use the seemingly scalar density() function for the arrays xx and yy as well.请注意,您不需要显式迭代网格网格,您也可以对 arrays xxyy使用看似标量的density() function。 For details about meshgrid , see this page .有关meshgrid的详细信息,请参阅此页面

Next simply use pcolormesh() to display or save.接下来只需使用pcolormesh()来显示或保存。

plt.pcolormesh(x, y, D)
plt.title('Density function = |x| + |y|')
plt.savefig('density.png')

The output is: output 是:

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM