NNsr NNsr - 4 months ago 33
Python Question

Multiply several matrices in numpy

Suppose you have n square matrices A1,...,An. Is there anyway to multiply these matrices in a neat way? As far as I know dot in numpy accepts only two arguments. One obvious way is to define a function to call itself and get the result. Is there any better way to get it done?

Answer

This might be a relatively recent feature, but I like:

A.dot(B).dot(C)

or if you had a long chain you could do:

reduce(numpy.dot, [A1, A2, ..., An])

Update:

There is more info about reduce here. Here is an example that might help.

>>> A = [np.random.random((5, 5)) for i in xrange(4)]
>>> product1 = A[0].dot(A[1]).dot(A[2]).dot(A[3])
>>> product2 = reduce(numpy.dot, A)
>>> numpy.all(product1 == product2)
True

Update 2016: As of python 3.5, there is a new matrix_multiply symbol, @:

R = A @ B @ C
Comments