I'm trying to vectorize a loop with NumPy but I'm stuck
I have a matrix A
of shape (NN,NN)
I define the A-dot product by
def scalA(u,v):
return v.T @ A @ u
Then I have two matrices B
and C
(B
has a shape (N,NN)
and C
has a shape (K,NN)
the loop I'm trying to vectorize is
res = np.zeros((N,K))
for n in range(N):
for k in range(K):
res[n,k] = scalA(B[n,:], C[k,:])
I found during my research functions like np.tensordot
or np.einsum
, but I haven't really understood how they work, and (if I have well understood) tensordot
will compute the canonical dot product (that would correspond to A = np.eye(NN)
in my case).
Thanks !
I think this works. I wrote it 'by eye' without testing.