Multiple matrix multiplication

喜夏-厌秋 提交于 2019-12-14 03:56:44

问题


In numpy, I have an array of N 3x3 matrices. This would be an example of how I'm storing them (I'm abstracting away the contents):

N = 10
matrices = np.ones((N, 3, 3))

I also have an array of 3-vectors, this would be an example:

vectors = np.ones((N, 3))

I can't seem to figure out how to multiply those via numpy, so as to achieve something like this:

result_vectors = []
for matrix, vector in zip(matrices, vectors):
    result_vectors.append(matrix @ vector)

with the result_vector's shape (upon casting to array) being (N, 3). However, a list implementation is out of the question due to speed.

I've tried np.dot with various transpositions, but the end result didn't get the shape right.


回答1:


Use np.einsum -

np.einsum('ijk,ik->ij',matrices,vectors)

Steps :

1) Keep the first axes aligned.

2) Sum-reduce the last axes from the input arrays against each other.

3) Let the remainining axes(second axis from matrices) be element-wise multiplied.



来源:https://stackoverflow.com/questions/41579458/multiple-matrix-multiplication

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!