I am trying to multiply to numpy arrays which both have the shape (2000,2,2). I want the outcome array to also have the shape (2000,2,2) where each of the 2000 (2,2) matrices of the first array have been matrix multiplied by the 2000 (2,2) matrices of the second array.
I have tried to use np.matmul() and numpy.dot() but I keep getting errors or unwanted results. For example, when using
a = np.ones(([2,2,2000]))
b = np.ones(([2,2,2000]))
np.matmul(a,b)
I get an error the dimensions are off (ValueError: matmul: Input operand 1 has a mismatch in its core dimension 0, with gufunc signature (n?,k),(k,m?)->(n?,m?) (size 2 is different from 2000)
, which makes sense. However, when multiplying as
np.matmul(a.T,b)
I get
ValueError: operands could not be broadcast together with remapped shapes [original->remapped]: (2000,2,2)->(2000,newaxis,newaxis) (2,2,2000)->(2,newaxis,newaxis) and requested shape (2,2000)
Is there a way to do this without making a for-loop?
CodePudding user response:
You could use the np.einsum()
function to specify the indices of the arrays that should be multiplied together like that:
result = np.einsum('ijk, ilk -> ijl', a, b)
This forms the sum over the last two indices of both arrays, resulting in the desired shape (2000, 2, 2).