# How to find the product of two matrices in python ?

Daidalos June 10, 2019

Examples of how to find the product of two matrices in python:

### Function dot()

To get the product of two matrices, a solution is to use the numpy function dot():

A = \left( \begin{array}{ccc}
1 & 2 & 0 \\
4 & 3 & -1
\end{array}\right)

B = \left( \begin{array}{ccc}
5 & 1 \\
2 & 3 \\
3 & 4
\end{array}\right)

C = A * B =
\left( \begin{array}{ccc}
1 & 2 & 0 \\
4 & 3 & -1
\end{array}\right)
*
\left( \begin{array}{ccc}
5 & 1 \\
2 & 3 \\
3 & 4
\end{array}\right)
=
\left( \begin{array}{ccc}
9 & 7 \\
23 & 9
\end{array}\right)

>>> import numpy as np
>>> A = np.array([[1,2,0],[4,3,-1]])
>>> A.shape
(2, 3)
>>> B = np.array([[5,1],[2,3],[3,4]])
>>> B.shape
(3, 2)
>>> C = A.dot(B)
>>> C
array([[ 9,  7],
       [23,  9]])


### The operator *

Warning: the * operator does not returns the product of two matrices, it returns the product of elements of same indexes.

Note: The two matrices must have the same size, example:

>>> import numpy as np
>>> A = np.array([[1,2,0],[4,3,-1]])
>>> C = np.array([[3,4,5],[1,2,3]])
>>> A * C
array([[ 3,  8,  0],
       [ 4,  6, -3]])


### Multiply by a constant

To multiply all the elements of a matrice by a constant:

>>> import numpy as np
>>> A = np.array([[1,2,0],[4,3,-1]])
>>> A * 2
array([[ 2,  4,  0],
       [ 8,  6, -2]])