25. Additional matrix operations#
There are many other linear algebra operations that are convenient to do in Python, and we will demonstrate them below.
Summary of commands#
In this exercise, we will use:
np.linalg.inv(A)- Compute the inverse of matrix \(A\).np.linalg.det(A)- Compute the determinant of matrix \(A\).np.linalg.solve(A, b)- Compute the solution \(\vec{x}\) in the equation \(A\vec{x} = \vec{b}\).
As before, these are all part of the linear algebra subroutine in NumPy.
Demo#
Consider the following matrices and vectors:
and compute the following:
(a) \(A^{-1}\)
(b) \(B^{-1}\)
(c) \(\mathrm{det}(A)\)
(d) \(\mathrm{det}(B)\)
(e) Solve the system \(A \vec{x} = \vec{b}\) for \(\vec{x}\).
(f) Solve the system \(B \vec{x} = \vec{b}\) for \(\vec{x}\).
import numpy as np
A = np.array([ [1, 3, 5], [2, 5, 10], [3, 3, 15] ])
B = np.array([ [2, 4, 5], [2, 5, 10], [3, 6, 9] ])
b = np.array([ [1], [4], [5] ])
print("Part (a)")
print(np.linalg.inv(A))
print()
Part (a)
[[ 5.40431955e+16 -3.60287970e+16 6.00479950e+15]
[ 2.00000000e+00 -1.00000000e+00 9.25185854e-18]
[-1.08086391e+16 7.20575940e+15 -1.20095990e+15]]
Beware!!
Matrix \(A\) is singular, and if you’re lucky, NumPy will spit out a LinAlgError.
Sometimes, however, it will still give a numerical result, where the array has values that are really big, i.e., \(\infty\), or really small, i.e., all \(0\).
Whenever it comes to numerical linear algebra, you should always be wary of floating-point errors.
print("Part (b)")
print(np.linalg.inv(B))
print()
print("Part (c)")
print(np.linalg.det(A))
print()
print("Part (d)")
print(np.linalg.det(B))
print()
print("Part (e)")
print(np.linalg.solve(A, b))
print()
Part (b)
[[-5.00000000e+00 -2.00000000e+00 5.00000000e+00]
[ 4.00000000e+00 1.00000000e+00 -3.33333333e+00]
[-1.00000000e+00 2.22044605e-16 6.66666667e-01]]
Part (c)
8.326672684688668e-16
Part (d)
3.000000000000002
Part (e)
[[-6.0047995e+16]
[-2.0000000e+00]
[ 1.2009599e+16]]
print("Part (f)")
print(np.linalg.solve(B, b))
print()
Part (f)
[[12. ]
[-8.66666667]
[ 2.33333333]]