I think I asked the wrong question yesterday. What I actually want is to mutiply two 2x2xN
matrices A
and B
, so that
C[:,:,i] = dot(A[:,:,i], B[:,:,i])
For example, if I have a matrix
A = np.arange(12).reshape(2, 2, 3)
How can I get C = A x A
with the definition described above? Is there a built-in function to do this?
Also, if I multiply A (shape 2x2xN)
with B (shape 2x2x1, instead of N)
, I want to get
C[:,:,i] = dot(A[:,:,i], B[:,:,1])
Try using numpy.einsum
, it has a little bit of a learning curve but it should give you what you want. Here is an example to get you started.
import numpy as np
A = np.random.random((2, 2, 3))
B = np.random.random((2, 2, 3))
C1 = np.empty((2, 2, 3))
for i in range(3):
C1[:, :, i] = np.dot(A[:, :, i], B[:, :, i])
C2 = np.einsum('ijn,jkn->ikn', A, B)
np.allclose(C1, C2)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With