Matrices

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

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

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

In [2]:
B = MS.basis()
show(list(B))

Now let's create two matrices

In [3]:
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 [4]:
show(A * B)

The same is true for addition

In [5]:
show(A + B) 

A special matrix is the identity matrix

In [6]:
I = MS.identity_matrix()
show(I)

Furthermore we do not necessarily need the object MS

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

It is also possible to create matrix with a lambda function

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

We can create a vector also with a function call:

In [9]:
v = vector((1, 2, 3))
v
Out[9]:
(1, 2, 3)

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

In [10]:
m * v
Out[10]:
(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 [11]:
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 [12]:
show(A * x)

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

In [13]:
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[13]:
[[x == a + 1, y == 2*a, z == a - 1]]

Other matrix operations and properties

In [14]:
m = matrix(QQ,[[1, 2], [2, 1]])
show(m)
show(m.determinant())
In [15]:
show(A.transpose())
In [16]:
show(m.inverse())

Eigenvalues and eigenvectors of matrices

In [17]:
m.eigenvalues()
Out[17]:
[3, -1]

Eigenvalues are the roots of the characteristic polyonomial:

In [18]:
m.charpoly('l')
Out[18]:
l^2 - 2*l - 3

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

In [19]:
show(m.eigenvectors_right())
In [20]:
show(m.eigenvectors_left())

Subspaces

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

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

Next we create a subspace

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

A subspace also has a basis

In [23]:
show(S.basis())