我有一些矩阵:
A = np.array([[0.8, 0.2],
[0.4, 0.6]])
B = np.array([0.4, 0.2])
C = np.array([0.28, 0.06])
我想做的是:
S = A.shape[0]
what_I_need = np.zeros([S])
for s in range(S):
what_I_need[s] = np.sum(A[:, s] * C) * B[s]
print(what_I_need)
结果是
[0.0992 0.0184]
有没有for循环的优雅或pythonic方法吗?谢谢
答案 0 :(得分:4)
使用matrix-multiplication
-
A.T.dot(C)*B # or C.dot(A)*B
只需一次致电np.einsum
-
np.einsum('ij,i,j->j',A,C,B) #use `optimize` flag for better perf.