我想从这个矩阵乘法中删除循环(并了解更多关于优化代码的知识),我认为我需要某种形式的np.broadcasting
或np.einsum
,但在阅读它们后,我仍然不确定如何将它们用于我的问题。
A = np.array([[1, 2, 3, 4, 5],
[6, 7, 8, 9, 10],
[11,12,13,14,15]])
#A is a 3x5 matrix, such that the shape of A is (3, 5) (and A[0] is (5,))
B = np.array([[1,0,0],
[0,2,0],
[0,0,3]])
#B is a 3x3 (diagonal) matrix, with a shape of (3, 3)
C = np.zeros(5)
for i in range(5):
C[i] = np.linalg.multi_dot([A[:,i].T, B, A[:,i]])
#Each row of matrix math is [1x3]*[3x3]*[3x1] to become a scaler value in each row
#C becomes a [5x1] matrix with a shape of (5,)
我知道我不能只使用np.multidot
,因为那会得到一个(5,5)的数组。
我还找到了这个:在Numpy中将矩阵乘以另一个矩阵的每一行,但我不确定它是否与我的问题实际上相同。