#imports
import numpy as np
from numpy import linalg
In this tutorial, we will make use of numpy's linalg
module.
# first, initialize new numpy array
a = np.array([[1],[2],[3]])
a
We can compute various norms using the linalg.norm
function:
linalg.norm(a) # L2 / Euclidean norm
linalg.norm(a, ord=1) # L1 norm
linalg.norm(a, ord=np.inf) # inf-norm / max norm
Computing the Determinant:
# initialize matrix A
A = np.array([[1,0,3],[4,-1,6],[7,8,3]])
A
# compute determinant
linalg.det(A)
# initialize matrix B
B = np.array([[1,2,3],[2,4,6],[3,6,9]])
B
# compute determinant
linalg.det(B)
# compute inverse
try:
linalg.inv(B) # throws exception because matrix is singular
except Exception as e:
print(e)
Computing eigenvalues and eigenvectors:
eigvals, eigvecs = linalg.eig(A)
print(eigvals) # vector of eigenvalues
print(eigvecs) # eigenvectors are columns of the matrix
Note that eig
does not guarantee that eigenvalues are returned in sorted order.
For symmetric matrices, use eigh
instead. This is more efficient and numerically reliable because it takes advantage of the fact that the matrix is symmetric. Moreover, the eigenvalues are returned in ascending order.
# initialize symmetric matrix
S = np.matmul(A, A.transpose())
S
eigvals, eigvecs = linalg.eigh(S)
print(eigvals)
print(eigvecs)
If you only want eigenvalues, you can use the linalg.eigvals
and linalg.eigvalsh
functions.
Let's try to recompose the matrix from eigenvalues and eigenvectors:
A
L, V = linalg.eig(A) # eigenvalues and eigenvectors
A_recomposed = np.matmul(V, np.matmul(np.diag(L), linalg.inv(V))) # recompose matrix
A_recomposed