简体   繁体   中英

Python vectorization of matrix-vector operation

I have a Matrix A with shape (2,2,N) and a Matrix V with shape (2,N)

I want to vectorize the following:

F = np.zeros(N)
for k in xrange(N):
    F[k] = np.dot( A[:,:,k], V[:,k] ).sum()

Any way this can be done with either tensordot or any other numpy function without explicit looping?

With np.einsum -

F = np.einsum('ijk,jk->k',A,V)

We can optimize it further with optimize flag (check docs) set as True .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM