Matrix
Matrix 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
Transposition, determinant, comatrix, inverse
A_T=A.T # Transpose A: -> 2D nparray: since A is an nparray, nupmy understands what you mean!
det_A=np.linalg.det(A): -> float
inverse_A=np.linalg.inv(A): -> 2D nparray
Element-wise,column-wise, and row-wise sum
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