How to find the product of two matrices in python ?

June 10, 2019    /    Viewed: 1269    /    Comments: 0    /    Edit


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():

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

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

\begin{equation}
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)
\end{equation}

>>> 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]])

References

Links Site
numpy.dot numpy doc
Produit matriciel wikipedia


Card image cap
profile-image
Daidalos

Je développe le présent site avec le framework python Django. Je m'intéresse aussi actuellement dans le cadre de mon travail au machine learning pour plusieurs projets (voir par exemple) et toutes suggestions ou commentaires sont les bienvenus !