In numpy, the numpy.dot()
function can be used to calculate the matrix product of two 2D arrays. I have two 3D arrays X and Y (say), and I'd like to calculate the matrix Z where Z[i] == numpy.dot(X[i], Y[i])
for all i
. Is this possible to do non-iteratively?
Asked
Active
Viewed 4,136 times
9

Ben Kirwin
- 164
- 2
- 8
-
Over what axis/axes are you wanting to do the product? For the case where X and Y were both 3x3, what is the size of Z? – talonmies Jun 10 '11 at 02:51
-
@talonmies If the two 3D arrays are K x L x M and K x M x N, the result should be K x L x N. – Ben Kirwin Jun 11 '11 at 16:12
1 Answers
8
How about:
from numpy.core.umath_tests import inner1d
Z = inner1d(X,Y)
For example:
X = np.random.normal(size=(10,5))
Y = np.random.normal(size=(10,5))
Z1 = inner1d(X,Y)
Z2 = [np.dot(X[k],Y[k]) for k in range(10)]
print np.allclose(Z1,Z2)
returns True
Edit Correction since I didn't see the 3D part of the question
from numpy.core.umath_tests import matrix_multiply
X = np.random.normal(size=(10,5,3))
Y = np.random.normal(size=(10,3,5))
Z1 = matrix_multiply(X,Y)
Z2 = np.array([np.dot(X[k],Y[k]) for k in range(10)])
np.allclose(Z1,Z2) # <== returns True
This works because (as the docstring states), matrix_multiply
provides
matrix_multiply(x1, x2[, out]) matrix
multiplication on last two dimensions
-
-
@DSM - yeah, missed that originally. I now have the corrected solution. – JoshAdel Jun 10 '11 at 03:20
-
The corrected version looks good... thanks! I'm sorry if my initial question was not clear. – Ben Kirwin Jun 11 '11 at 16:13
-
@hass: your question was clear, I just missed it when I read it the first time. Glad I could be of help. – JoshAdel Jun 11 '11 at 23:00