from sympy import *
init_printing()
x, y, z = symbols('x,y,z')
r, theta = symbols('r,theta', positive=True)
%load_ext exercise
The SymPy Matrix
object helps us with small problems in linear algebra.
rot = Matrix([[r*cos(theta), -r*sin(theta)],
[r*sin(theta), r*cos(theta)]])
rot
rot.det()
rot.inv()
rot.singular_values()
Find the inverse of the following Matrix:
$$ \left[\begin{matrix}1 & x\\y & 1\end{matrix}\right] $$# Create a matrix and use the `inv` method to find the inverse
The standard SymPy operators work on matrices.
rot * 2
rot**2
v = Matrix([[x], [y]])
v
rot * v
In the last exercise you found the inverse of the following matrix
M = Matrix([[1, x], [y, 1]])
M
M.inv()
Now verify that this is the true inverse by multiplying the matrix times its inverse. Do you get the identity matrix back?
# Multiply `M` by its inverse. Do you get back the identity matrix?
What are the eigenvectors and eigenvalues of M
?
# Find the methods to compute eigenvectors and eigenvalues. Use these methods on `M`
rot[0, 0]
rot[:, 0]
rot[1, :]
We can change elements in the matrix.
rot[0, 0] += 1
rot
simplify(rot.det())
rot.singular_values()
Matrix Constructors can be used for making special types of Matrices quickly and efficiently.
eye(3)
diag(1, 2, 3)
ones(3, 3)
zeros(3, 3)
diag(eye(2), 1) # eye(3)
Use the matrix constructors to construct the following matrices. There may be more than one correct answer.
# %exercise exercise_matrix1.py
def matrix1():
"""
>>> matrix1()
[4, 0, 0]
[0, 4, 0]
[0, 0, 4]
"""
return diag(eye(2)*4, 4)
matrix1()
# %exercise exercise_matrix2.py
def matrix2():
"""
>>> matrix2()
[1, 1, 1, 0]
[1, 1, 1, 0]
[0, 0, 0, 1]
"""
return ???
matrix2()
# %exercise exercise_matrix3.py
def matrix3():
"""
>>> matrix3()
[-1, -1, -1, 0, 0, 0]
[-1, -1, -1, 0, 0, 0]
[-1, -1, -1, 0, 0, 0]
[ 0, 0, 0, 0, 0, 0]
[ 0, 0, 0, 0, 0, 0]
[ 0, 0, 0, 0, 0, 0]
"""
return ???
matrix3()
Play around with your matrix M
, manipulating elements in a NumPy like way. Then try the various methods that we've talked about (or others). See what sort of answers you get.
# Play with matrices