Sometime back this question (now deleted but 10K+ rep users can still view it) was posted. It looked interesting to me and I learnt something new there while trying to solve it and I thought that's worth sharing. I would like to post those ideas/solutions and would love to see people post other possible ways to solve it. I am posting the gist of the question next.
So, we have two NumPy ndarrays a and b of shapes :
a : (m,n,N)
b : (n,m,N)
Let's assume we are dealing with cases where m,n & N are comparable.
The problem is to solve the following multiplication and summation with focus on performance :
def all_loopy(a,b):
P,Q,N = a.shape
d = np.zeros(N)
for i in range(N):
for j in range(i):
for k in range(P):
for n in range(Q):
d[i] += a[k,n,i] * b[n,k,j]
return d