I want to compute the following operation over a matrix :
import numpy as np
x = np.arange(9).reshape((3,3))
result = np.zeros((3,3,3))
for i in range(3):
for j in range(3):
for k in range(3):
result[i,j,k] = x[j,i] * x[j,k]
Which gives
array([[[ 0., 0., 0.],
[ 9., 12., 15.],
[ 36., 42., 48.]],
[[ 0., 1., 2.],
[ 12., 16., 20.],
[ 42., 49., 56.]],
[[ 0., 2., 4.],
[ 15., 20., 25.],
[ 48., 56., 64.]]])
As expected.
Question
How can I perform this calculation with tensor products (without loops) with numpy ?
Edit
If the elements of X are vectors, the operation is instead :
result[i,j,k] = np.dot(x[j,i] , x[j,k])
What would be the appropriate numpy operator for this calculation ?