在 Python 中获取笛卡尔网格的坐标点列表

计算科学 Python
2021-11-26 04:53:45

我有一个常规的三维笛卡尔网格numpy.linspace(a1,an,na), numpy.linspace(b1,bn,nb), numpy.linspace(c1,cn,nc)以及它们各自的尺寸。

我现在想在所有点上评估一个函数(ai,bj,ck)在这个网格上。该函数f(list_of_points,*args)采用点列表并返回每个点的标量函数值列表。

是否有函数 a) 将笛卡尔网格显示为列表,以便我可以轻松地将其用于此函数,然后 b) 允许将返回的标量列表轻松重新格式化为维度数组(na,nb,nc)

1个回答

您可能正在寻找np.meshgrid(). 通过示例最容易了解它是如何工作的:

>>> import numpy as np

# Start with three different 1-D arrays, possibly with different sizes.
>>> a = np.random.random(10)
>>> b = np.random.random(15)
>>> c = np.random.random(20)

# Use np.meshgrid() to create 3-D arrays by joining the three 1-D arrays.
>>> A, B, C = np.meshgrid(a, b, c, indexing="ij")
>>> print(A.shape, B.shape, C.shape)
(10, 15, 20) (10, 15, 20) (10, 15, 20)

# It's easy to use these arrays for computations like x_ijk = a_i + b_j * c_k.
>>> X = A + B * C

# Let's do this with loops to check that we get the same result.
>>> Y = np.empty((10, 15, 20))
>>> for i in range(a.size):                    # i = 0, ..., 9
...     for j in range(b.size):                # j = 0, ..., 14
...         for k in range(c.size):            # k = 0, ..., 19
...             Y[i,j,k] = a[i] + b[j] * c[k]  # y_ijk = a_i + b_j * c_k
... 
>>> np.allclose(X,Y)
True

这使您可以在所需的网格上以一种高效、易读的方式计算任何标量值函数只要记住在适用的情况下使用 NumPy 函数(例如,而不是)。f:(a,b,c)Rnp.sin()math.sin()

例如,如果,首先定义网格数组, , 和, 用于获取, , 和, 和 设置f(a,b,c)=sin(a)b2+ecabcnp.meshgrid()ABCF = np.sin(A) * B**2 + np.exp(C)