如何在python中对以下四个for循环进行矢量化?

如何在python中对以下四个for循环进行矢量化?,python,for-loop,vectorization,Python,For Loop,Vectorization,我必须构造一个大小为(Nx*Ny,Nx*Ny)的矩阵,其中Nx和Ny可以大于100。目前我正在使用四个for循环,这使得我的最终矩阵“矩阵结果”(具有维度(Nx*Ny,Nx*Ny))的初始化非常缓慢 前两个循环覆盖数组xs和ys中的所有元素。后两个循环同样位于xs和ys中的相同元素上。然后我用matrix\u idx=idx\u y1+Ny*idx\u x和matrix\u idy=idx\u y2+Ny*idx\u x2构造矩阵结果的x索引和y索引 这是完整的代码。如何对矩阵“矩阵结果”的初始

我必须构造一个大小为
(Nx*Ny,Nx*Ny)
的矩阵,其中
Nx
Ny
可以大于100。目前我正在使用四个for循环,这使得我的最终矩阵“矩阵结果”(具有维度
(Nx*Ny,Nx*Ny)
)的初始化非常缓慢

前两个循环覆盖数组xs和ys中的所有元素。后两个循环同样位于xs和ys中的相同元素上。然后我用
matrix\u idx=idx\u y1+Ny*idx\u x
matrix\u idy=idx\u y2+Ny*idx\u x2
构造矩阵结果的x索引和y索引

这是完整的代码。如何对矩阵“矩阵结果”的初始化进行矢量化

我发现要解释这个问题很难,但据我所知,这确实符合你的要求

通常,可以使用np.index对嵌套for循环集进行向量化

xs = np.random.rand(40)
ys = np.random.rand(40)
s = time.time()
func1(xs, ys)
print("time taken for original:", time.time() - s)
s = time.time()
func2(xs, ys)
print("time taken for vectorised:", time.time() - s)
原件所用时间:19.610620737075806

矢量化所用时间:0.3943142890930176

与:

使用plt.imshow时,您将获得以下输出:


代码回答了我的问题!对不起,问的时候不清楚。我有一个2D网格(xs和ys)。代替二维网格,我必须定义一个新的二维网格,其中包含二维网格点的所有点作为其x坐标(与y坐标类似,因此新的尺寸是
(Nx*Ny,Nx*Ny)
)。同时,新矩阵的元素仍然依赖于“旧”二维网格。谢谢你的回答!
def vectorised_calculation(xs, xy):
    Nx = len(xs)
    Ny = len(ys)
    matrix_result = np.zeros((Nx * Ny, Nx * Ny))

    indices = np.indices([Nx,Ny,Nx,Ny])
    #Remove those sets of indices that do not satisfy the following condition
    mask = np.logical_or(indices[0] != indices[2], indices[1] != indices[3])
    indices = indices[:, mask]

    x1 = xs[indices[0]]
    y1 = ys[indices[1]]
    x2 = xs[indices[2]]
    y2 = ys[indices[3]]
    argument1 = np.arctan2(y1,x1)
    argument2 = np.arctan2(y2,x2)
    
    # Compute the elements of the matrix matrix_results.
    distance_12 = np.sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2)
    matrix_element = np.cos(argument2 - argument1) * np.exp(distance_12)
        
    # Construct indices of the matrix matrix_result with dimension (Nx * Ny,     Nx *     Ny)
    matrix_idx = indices[1] + Ny * indices[0]
    matrix_idy = indices[3] + Ny * indices[2]
        
    # Insert elements into matrix
    matrix_result[matrix_idx, matrix_idy] = matrix_element

    return matrix_result
xs = np.random.rand(40)
ys = np.random.rand(40)
s = time.time()
func1(xs, ys)
print("time taken for original:", time.time() - s)
s = time.time()
func2(xs, ys)
print("time taken for vectorised:", time.time() - s)
xs = np.linspace(0.0, 2.0, 100)
ys = np.linspace(0.0, 2.0, 100)