Master essential linear algebra operations with Python using the NumPy library. This cheat sheet includes matrix operations, decompositions, eigenvalues, and more.
1. Importing NumPy
import numpy as np
2. Creating Matrices
# Create a 2x2 matrix
A = np.array([[1, 2], [3, 4]])
# Create a 3x3 identity matrix
I = np.eye(3)
print(A)
print(I)
Output:
[[1 2] [3 4]] [[1. 0. 0.] [0. 1. 0.] [0. 0. 1.]]
3. Matrix Transpose
# Transpose a matrix
A_T = A.T
print(A_T)
Output:
[[1 3] [2 4]]
4. Matrix Addition and Subtraction
# Add or subtract matrices
B = np.array([[5, 6], [7, 8]])
C_add = A + B
C_sub = A - B
print(C_add)
print(C_sub)
Output:
[[ 6 8] [10 12]] [[-4 -4] [-4 -4]]
5. Matrix Multiplication
# Matrix multiplication
C_mult = np.dot(A, B)
print(C_mult)
Output:
[[19 22] [43 50]]
6. Determinant of a Matrix
# Compute the determinant
det_A = np.linalg.det(A)
print(det_A)
Output:
-2.0
7. Matrix Inverse
# Compute the inverse
A_inv = np.linalg.inv(A)
print(A_inv)
Output:
[[-2. 1. ] [ 1.5 -0.5]]
8. Solving Linear Systems
# Solve Ax = b
b = np.array([5, 6])
x = np.linalg.solve(A, b)
print(x)
Output:
[-4. 4.5]
9. Eigenvalues and Eigenvectors
# Compute eigenvalues and eigenvectors
eigenvalues, eigenvectors = np.linalg.eig(A)
print(eigenvalues)
print(eigenvectors)
Output:
[ 5.37228132 -0.37228132] [[ 0.41597356 -0.82456484] [ 0.90937671 0.56576746]]
10. Singular Value Decomposition (SVD)
# Perform SVD
U, S, V = np.linalg.svd(A)
print("U:", U)
print("S:", S)
print("V:", V)
Output:
U: [[-0.40455358 -0.9145143 ] [-0.9145143 0.40455358]] S: [5.4649857 0.36596619] V: [[-0.57604844 -0.81741556] [ 0.81741556 -0.57604844]]
11. Norm of a Matrix
# Compute the Frobenius norm
norm_A = np.linalg.norm(A)
print(norm_A)
Output:
5.477225575051661
12. Diagonal and Trace of a Matrix
# Extract diagonal
diag_A = np.diag(A)
print(diag_A)
# Compute trace
trace_A = np.trace(A)
print(trace_A)
Output:
[1 4] 5
13. Generating Random Matrices
# Random matrix (3x3)
rand_matrix = np.random.rand(3, 3)
print(rand_matrix)
Output:
[[0.37454012 0.95071431 0.73199394] [0.59865848 0.15601864 0.15599452] [0.05808361 0.86617615 0.60111501]]