# Matrices¶

Create a set of 2x2 matrices where the entries are rational numbers:

In :
MS = MatrixSpace(QQ, 2)
show(MS.dims())


A basis is a set of elements generating the entire set of vectors as linear combinations.

In :
B = MS.basis()
show(list(B))


Now let's create two matrices

In :
A = MS.matrix([1, 2, 3, 4])
B = MS.matrix([4, 3, 3, 4])
show(A)


Matrix multiplication is also quite easy with sagemath

In :
show(A * B)


The same is true for addition

In :
show(A + B)


A special matrix is the identity matrix

In :
I = MS.identity_matrix()
show(I)


Furthermore we do not necessarily need the object MS

In :
m = matrix(QQ, [[1, 2], [4, 5]])
show(m)


It is also possible to create matrix with a lambda function

In :
m = matrix(QQ, 3, 3, lambda r, c: max(r, c))
show(m)


We can create a vector also with a function call:

In :
v = vector((1, 2, 3))
v

Out:
(1, 2, 3)

We can also multiply matrices and vectors using the * operator:

In :
m * v

Out:
(8, 9, 12)

## Linear equation systems¶

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:

In :
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:

In :
show(A * x)


You can even solve equations without matrices (example from the sagemath documentation):

In :
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)

Out:
[[x == a + 1, y == 2*a, z == a - 1]]

## Other matrix operations and properties¶

In :
m = matrix(QQ,[[1, 2], [2, 1]])
show(m)
show(m.determinant())

In :
show(A.transpose())

In :
show(m.inverse())


## Eigenvalues and eigenvectors of matrices¶

In :
m.eigenvalues()

Out:
[3, -1]

Eigenvalues are the roots of the characteristic polyonomial:

In :
m.charpoly('l')

Out:
l^2 - 2*l - 3

Eigenvectors for general matrices are given as right-sided vectors and left-sided vectors:

In :
show(m.eigenvectors_right())

In :
show(m.eigenvectors_left())


## Subspaces¶

Subspaces lead us to vectorspaces. This will create a vector space of the dimension 3:

In :
V = VectorSpace(GF(4), 3)
show(V)


Next we create a subspace

In :
S = V.subspace([V([1, 1, 0]), V([4, 0, 1])])


A subspace also has a basis

In :
show(S.basis())