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?
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.
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.
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.
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
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