Numpy: Multiplying arrays of matrices
Andre Alexander Bell
post at andre-bell.de
Thu Sep 16 02:24:03 EDT 2010
Hi,
I assume you have arrays like these:
>>> import numpy as np
>>> m1 = np.random.rand(size=(4,3,3))
>>> m2 = np.random.rand(size=(4,3,3))
So that m1[0] is a 3x3 Matrix and m1[1] is another one, i.e. you have
four matrices.
On 09/15/2010 01:54 AM, Gregory Ewing wrote:
> I had thought that dot() might do this, but it appears
> not, because e.g. applying it to two 3-d arrays gives
> a 4-d array, not another 3-d array.
You now want to compute the matrixproducts like this
>>> np.dot(m1[0], m2[0])
and most likely you want to do this for all of the pairs
>>> m1m2 = np.array(map(lambda (a,b): np.dot(a,b), zip(m1,m2)))
or you could write the loop
>>> m1m2 = np.empty_like(m1)
>>> for i in range(m1m2.shape[0]):
... m1m2[i] = np.dot(m1, m2)
which might scale better
> I'd also like to be able to find the inverse of each
> matrix in one of these arrays, but again, inv() doesn't
> do what I want -- it only works on 2-d arrays.
Same as before
>>> m1inv = np.array(map(np.linalg.inv, m1))
or writing the loop
>>> m1inv = np.empty_like(m1)
>>> for i in range(m1inv.shape[0]):
... m1inv[i] = np.linalg.inv(m1[i])
Once again, I'm not sure whether or not it is acceptable to have the
overhead of treating the array as a list.
Andre
More information about the Python-list
mailing list