问题
I have a set of matrices collected in a 3-D array with shape (1222, 47, 47)
, and a set of vectors in a 2-D array with shape (1222, 47)
.
Is there a broadcasting way to multiply each [47x47] matrix with its corresponding [47] vector? With a full loop, this would be
numpy.vstack([A[n, :, :].dot(xb[n, :]) for n in range(A.shape[0])])
which is okay for 1222 elements, but I might have a lot more later. I tried if dot
, matrix_multiply
, inner
, or inner1d
would fit the bill, in combination with transpose
, but I didn't quite get it. Can this be done?
回答1:
Any of these should do it:
matrix_multiply(matrices, vectors[..., None])
np.einsum('ijk,ik->ij', matrices, vectors)
None will take advantage of a highly optimized library though.
Sometime in the future, when PEP 465 has been implemented, using Python >= 3.5 you should be able to simply do:
matrices @ vectors[..., None]
来源:https://stackoverflow.com/questions/24174045/broadcasting-matrix-vector-dot-product