python - numpy:使用一维和二维数组进行切片和矢量化循环

标签 python numpy multidimensional-array indexing slice

我想对以下循环进行矢量化以提高效率:

A = np.array([[0., 1., 0., 2.],
              [1., 0., 3., 0.],
              [0., 0., 0., 4.],
              [2., 0., 4., 0.]]) # quadratic, not symmetric Matrix, shape (i, i)
B = np.array([2., 4., 2., 1.]) # vector shape (i)
C = np.zeros(A.shape) # Result Matrix 
# classical Loop:
for i in range(len(B)):
    for j in range(len(B)):
        C[i, j] = A[i, j]*(B[i]-B[j])

我的第一次尝试,像在 Mathcad 中一样使用矢量化,并不是我想要的:

i = np.arange(len(B))
j = np.arange(len(B))
C[i,j] = A[i,j]*(B[i]-B[j]) # this fails to do what I want

我的第二次尝试是最好的方法吗,还是有更简单、更自然的“numpy 方法”?

idx = np.indices(A.shape)
C[idx] = A[idx]*(B[idx[0]]-B[idx[1]])

最佳答案

以下内容符合您的要求:

A = np.array([[0., 1., 0., 2.],
             [1., 0., 3., 0.],
             [0., 0., 0., 4.],
             [2., 0., 4., 0.]]) # quadratic, not symmetric Matrix, shape (i, i)
B = np.array([2., 4., 2., 1.]) # vector shape (i)

C = A*(B[:,None]-B)

C 是

array([[ 0., -2.,  0.,  2.],
       [ 2.,  0.,  6.,  0.],
       [ 0., -0.,  0.,  4.],
       [-2., -0., -4.,  0.]])

一点解释:
B[:,None]B 转换为形状为 [4,1] 的列向量。 B[:,None]-B 自动将结果广播到 4x4 矩阵,您只需乘以 A

关于python - numpy:使用一维和二维数组进行切片和矢量化循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16142829/

相关文章:

python - 使用打印的意外输出

python - 当两个值相同时,如何将 pandas 数据框列的值与变量进行比较以获得总和?

python - Numpy 追加到一个空数组

python - 使用 "del np.dtype"后,重新导入 numpy 是否应该修复此问题?

python - numpy ndarray 是均匀的和矩形的(子数组必须具有相同的长度)因为它在引擎盖下使用 C 数组吗?

python - 模拟范围超出当前测试

python - einsums 的 numpy 组成?

c - 如何从字符串文字创建多维数组

objective-c - 获取n维数组中的下一个元素

python - 可以在使用点而不是文件顶部导入依赖项吗?