In this notebook, we'll see how to add/subtract matrices, perform matrix multiplication, solve linear systems and find eigenvalues and eigenvectors numerically. This is a nice way to check answers to problems as well as a much faster way to perform matrix computations, particularlly for large matrices. You'll still need to be able to do all of these things by hand for the exam.
import scipy.linalg as spl # Matrix operations can be handled in python with the scipy or numpy linear algebra libraries
import numpy as np
# Set up two matrices
A = np.array([
[-1, 2, 1],
[3, 1, 2],
[1, 0, 3]
])
B = np.array([
[1, -2, 3],
[-2, -1, -2],
[1, 0, -3]
])
# Add the matrices
print(A + B)
[[0 0 4] [1 0 0] [2 0 0]]
# Subtract them
print(A - B)
[[-2 4 -2] [ 5 2 4] [ 0 0 6]]
# Multiply elementwise
print(A * B)
[[-1 -4 3] [-6 -1 -4] [ 1 0 -9]]
# Dot product
print(np.dot(A,B))
[[ -4 0 -10] [ 3 -7 1] [ 4 -2 -6]]
# Another way to do the dot product
print(A @ B)
[[ -4 0 -10] [ 3 -7 1] [ 4 -2 -6]]
# Find the determinant
print(spl.det(B))
22.0
# Find the inverse
print(spl.inv(A))
[[-0.16666667 0.33333333 -0.16666667] [ 0.38888889 0.22222222 -0.27777778] [ 0.05555556 -0.11111111 0.38888889]]
# Solve a linear system of the Ax = b form.
# We found the answer by hand in Q2 of the practise problems, it was x = (2, -3, 5)
A = np.array([
[1,3,2],
[2, -1, -3],
[5, 2, 1]
])
b = np.array([3, -8, 9])
x = spl.solve(A,b)
print(x)
[ 2. -3. 5.]
# We can also find eigenvalues and eigenvectors
# In Q3 of the practise problems, we found analytically that the eigenvalues were lm1 = 1,lm2 = 4,lm3 = 2 and the eigenvectors were
# v1 = (-2,1,0), v2 = (0,1,1), v3 = (-2, 1, 1) .
# You'll notice that when found numerically, eigenvectors are normalised to have unit length.
A = np.array([
[2, 2, -2],
[1, 3, 1],
[1, 2, 2]
])
evals, evecs = spl.eig(A)
for i in range(len(evals)):
print("lm = {0}, v = {1}".format(evals[i], evecs[:,i]))
lm = (3.9999999999999973+0j), v = [ 5.55111512e-16 -7.07106781e-01 -7.07106781e-01] lm = (2.000000000000002+0j), v = [-0.81649658 0.40824829 0.40824829] lm = (0.999999999999999+0j), v = [ 8.94427191e-01 -4.47213595e-01 1.40433339e-16]