【发布时间】:2021-05-04 06:54:44
【问题描述】:
我必须构造一个大小为(Nx*Ny, Nx*Ny) 的矩阵,其中Nx 和Ny 可以大于100。目前我正在使用四个for 循环来初始化我的最终矩阵“matrix_result”(具有维度(Nx*Ny, Nx*Ny)) 很慢。
前两个循环遍历数组 xs 和 ys 中的所有元素。后两个循环再次遍历 xs 和 ys 中的相同元素。然后我用matrix_idx = idx_y1 + Ny * idx_x和matrix_idy = idx_y2 + Ny * idx_x2构造matrix_result的x-index和y-index。
这是完整的代码。如何向量化矩阵“matrix_result”的这些初始化?
import numpy as np
Nx = 100
Ny = 100
xs = np.linspace(0.0, 2.0, Nx)
ys = np.linspace(0.0, 2.0, Ny)
matrix_result = np.zeros((Nx * Ny, Nx * Ny))
for idx_x1 in range(Nx):
for idx_y1 in range(Ny):
# Get values of the arrays xs and ys
x1 = xs[idx_x1]
y1 = ys[idx_y1]
# Compute arctan2 of y1 and x1
argument1 = np.arctan2(y1, x1)
for idx_x2 in range(Nx):
for idx_y2 in range(Ny):
if idx_x1 != idx_x2 or idx_y1 != idx_y2:
# Get values of the arrays xs and ys
x2 = xs[idx_x2]
y2 = ys[idx_y2]
# Compute arctan2 of y1 and 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 = idx_y1 + Ny * idx_x1
matrix_idy = idx_y2 + Ny * idx_x2
# Insert elements into matrix
matrix_result[matrix_idx, matrix_idy] = matrix_element
【问题讨论】:
标签: python for-loop vectorization