Create a set of 2x2 matrices where the entries are rational numbers:
MS = MatrixSpace(QQ, 2)
show(MS.dims())
A basis is a set of elements generating the entire set of vectors as linear combinations.
B = MS.basis()
show(list(B))
Now let's create two matrices
A = MS.matrix([1, 2, 3, 4])
B = MS.matrix([4, 3, 3, 4])
show(A)
Matrix multiplication is also quite easy with sagemath
show(A * B)
The same is true for addition
show(A + B)
A special matrix is the identity matrix
I = MS.identity_matrix()
show(I)
Furthermore we do not necessarily need the object MS
m = matrix(QQ, [[1, 2], [4, 5]])
show(m)
It is also possible to create matrix with a lambda function
m = matrix(QQ, 3, 3, lambda r, c: max(r, c))
show(m)
We can create a vector also with a function call:
v = vector((1, 2, 3))
v
We can also multiply matrices and vectors using the *
operator:
m * v
A common use of matrices are linear equations. These can be solved using numpy.
The first output is the Hilbert matrix and the second the solution of the linear equation system:
from numpy import linalg
A = matrix.hilbert(2)
show(A)
b = vector((1,1))
x = linalg.solve(A, b)
x = vector(x)
show(x)
Let's verify that sagemath is right:
show(A * x)
You can even solve equations without matrices (example from the sagemath documentation):
var('x,y,z,a')
eqns = [x + z == y, 2*a*x - y == 2*a^2, y - 2*z == 2]
solve(eqns, x, y, z)
m = matrix(QQ,[[1, 2], [2, 1]])
show(m)
show(m.determinant())
show(A.transpose())
show(m.inverse())
m.eigenvalues()
Eigenvalues are the roots of the characteristic polyonomial:
m.charpoly('l')
Eigenvectors for general matrices are given as right-sided vectors and left-sided vectors:
show(m.eigenvectors_right())
show(m.eigenvectors_left())
Subspaces lead us to vectorspaces. This will create a vector space of the dimension 3:
V = VectorSpace(GF(4), 3)
show(V)
Next we create a subspace
S = V.subspace([V([1, 1, 0]), V([4, 0, 1])])
A subspace also has a basis
show(S.basis())