2
循環我想向量化下面的循環效率:numpy的:切片和矢量與一維和二維數組
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]])
請問您可以編輯修改'B = np.array [2。,4.,2.,1.]'到'B = np.array([2,4,2,1。])'? (我沒有做這樣一個小edi的聲望) – 2013-04-22 14:27:41