#!/usr/bin/env python # coding: utf-8 # In[ ]: #imports import numpy as np from numpy import linalg # In this tutorial, we will make use of numpy's ```linalg``` module. # In[ ]: # first, initialize new numpy array a = np.array([[1],[2],[3]]) a # --- # We can compute various norms using the ```linalg.norm``` function: # In[ ]: linalg.norm(a) # L2 / Euclidean norm # In[ ]: linalg.norm(a, ord=1) # L1 norm # In[ ]: linalg.norm(a, ord=np.inf) # inf-norm / max norm # --- # Computing the Determinant: # In[ ]: # initialize matrix A A = np.array([[1,0,3],[4,-1,6],[7,8,3]]) A # In[ ]: # compute determinant linalg.det(A) # In[ ]: # initialize matrix B B = np.array([[1,2,3],[2,4,6],[3,6,9]]) B # In[ ]: # compute determinant linalg.det(B) # In[ ]: # compute inverse try: linalg.inv(B) # throws exception because matrix is singular except Exception as e: print(e) # --- # Computing eigenvalues and eigenvectors: # In[ ]: eigvals, eigvecs = linalg.eig(A) # In[ ]: print(eigvals) # vector of eigenvalues # In[ ]: 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. # In[ ]: # initialize symmetric matrix S = np.matmul(A, A.transpose()) S # In[ ]: eigvals, eigvecs = linalg.eigh(S) # In[ ]: print(eigvals) # In[ ]: 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: # In[ ]: A # In[ ]: L, V = linalg.eig(A) # eigenvalues and eigenvectors # In[ ]: A_recomposed = np.matmul(V, np.matmul(np.diag(L), linalg.inv(V))) # recompose matrix A_recomposed # In[ ]: