Matrix: Difference between revisions
Jump to navigation
Jump to search
Created page with "== Matrice operations in python == === Initialisation === <syntaxhighlight lang=python copy> import numpy as np # import numpy </syntaxhighlight> The matrices are to be inputted as 2D numpy arrays, so: $$ \forall a_{ij} \in \mathbf{A}, \text{a[i][j]}=a_{ij} $$ For example, to initialise the identity matrice $\mathbf{I}_3$: $$ I=\begin{pmatrix}1&0&0\\0&1&0\\0&0&1\end{pmatrix} $$ <syntaxhighlight lang=python copy> I=np.array([[1,0,0],[0,1,0],[0,0,1]]) </syntaxhighli..." |
|||
| Line 4: | Line 4: | ||
<syntaxhighlight lang=python copy> | <syntaxhighlight lang=python copy> | ||
import numpy as np # import | import numpy as np # import dependencies: always the 1st step! | ||
</syntaxhighlight> | </syntaxhighlight> | ||
Revision as of 07:15, 15 October 2026
Matrice operations in python
Initialisation
import numpy as np # import dependencies: always the 1st step!
The matrices are to be inputted as 2D numpy arrays, so:
$$ \forall a_{ij} \in \mathbf{A}, \text{a[i][j]}=a_{ij} $$
For example, to initialise the identity matrice $\mathbf{I}_3$:
$$ I=\begin{pmatrix}1&0&0\\0&1&0\\0&0&1\end{pmatrix} $$
I=np.array([[1,0,0],[0,1,0],[0,0,1]])
For two matrices $\mathbf{A},\mathbf{B}$ initialised as 2D arrays:
Single matrix operations
A_T=A.T # Transpose A: -> 2D nparray: since A is an nparray, nupmy understands what you mean!
sum_A=np.sum(A) # -> float: element-wise sum of A
column_wise_sum=np.sum(A, axis=0): -> 1D nparray
row_wise_sum=np.sum(A, axis=1): -> 1D nparray
Two matrices operations
Element-wise operations
sum_A_B=np.add(A,B) # A+B
difference_A_B=np.subtract(A,B) # A-B
element_wise_product_A_B=np.multiply(A,B) # A \circ B
quotient_A_B=np.divide(A,B) # A/B
Be extremely careful with
np.multiply, which gives the element-wise product, NOT the matrix product.
Matrix operations
product_A_B=np.dot(A,B) # A.B