Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiply several matrices in numpy

Tags:

python

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?

like image 594
NNsr Avatar asked Aug 07 '12 02:08

NNsr


People also ask

How do you multiply multiple matrices?

To perform multiplication of two matrices, we should make sure that the number of columns in the 1st matrix is equal to the rows in the 2nd matrix. Therefore, the resulting matrix product will have a number of rows of the 1st matrix and a number of columns of the 2nd matrix.

How do you multiply multiple arrays in Python?

multiply() in Python. numpy. multiply() function is used when we want to compute the multiplication of two array. It returns the product of arr1 and arr2, element-wise.

How do you multiply all values in a NumPy array?

A Quick Introduction to Numpy Multiply You can use np. multiply to multiply two same-sized arrays together. This computes something called the Hadamard product. In the Hadamard product, the two inputs have the same shape, and the output contains the element-wise product of each of the input values.


1 Answers

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 
like image 55
Bi Rico Avatar answered Sep 21 '22 09:09

Bi Rico