I am working with Numpy on an image processing problem, and I am trying to avoid loops and do the following:
I have a matrix M of dims NxNxKxK (which is a matrix NxN of matrices KxK), and for each row, I wish to multiply (dot product) all the N matrices (KxK) in the row. So that if I do this on the full M (all of the rows) I get a vector V (Nx1) of matrices (KxK) where V[i] holds the dot product of M[i,0]xM[i,1]x...xM[i,N-1].
I implemented a solution to this problem using loops, and I can't figure out a way to do this without loops.
Implementation (with loops):
a = np.array([[1,1,1], [1,1,1], [1,1,1]])
mat = np.array([[a,a,a,a], [a*2,a*2,a*2,a*2], [a*3,a*3,a*3,a*3],
[a*4,a*4,a*4,a*4]]) # the original matrix
N, N, k, k = mat.shape
result = np.ones((N, k, k)) # resulting matrix
for i in range(N):
k = functools.reduce(np.dot, mat[i,:])
result[i,:] = k
print(result)
N
is 4. Is there an upper bound on how largeN
will be in your actual application? – Corbeil[a,a,a,a]
,[a*2,a*2,a*2,a*2]
, etc. ? – Springtimeeinsum
territory. – Hekatenp.einsum('ab,bc,cd,de,ef,fg,gh,hi', *factors[:8])
but it turns out to be much slower than the reduce method. – SpermogoniumKxK
matrices – Spermogoniumeinsum
doesn't seem to be a good solution anyway. – Spermogonium