Python vectorization of matrix-vector operation

155 Views Asked by At

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?

1

There are 1 best solutions below

0
On BEST ANSWER

With np.einsum -

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

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