We have already seen several functions that take, or can take, matrices as inputs (e.g. det, t(), solve, diag). However, we can also write our functions involving matrices.
As a simple first example, suppose we want to write a function that returns the trace (i.e. the sum of the diagonal elements) of a square matrix. Note that we already know how to extract the diagonal elements of a matrix using the function diag.
Trace <- function(A) {
diag_e <- diag(A)
trace <- sum(diag_e)
return(trace)
}
As a more complicated example, we can consider writing a function to determine whether a supplied square matrix is nilpotent and if so, to what degree.
A matrix is nilpotent with degree , where is a positive integer, if and for all positive integers .
To help us develop the function, we can note that if a matrix is nilpotent it must be nilpotent with degree less than or equal to the dimension of the matrix. We can check whether a particular matrix is equal to the zero matrix by obtaining the maximum absolute entry of the matrix. We can also use the fact that nilpotent matrices must have determinant equal to zero. In each case, a suitable tolerance limit is required, because R will introduce some small rounding error. Here we take .
nilpotent <- function(A) {
dm <- dim(A)[1]
if (abs(det(A))> 1e-8) return("Matrix is not nilpotent")
if (max(abs(A))< 1e-8) return(1)
An <- A
for (n in 2:dm) {
An <- An%*%A
if (max(abs(An))< 1e-8) return(n)
}
return("Matrix is not nilpotent")
}
Quiz 1: System of linear equations
Find the value for , , , and that satisfies these linear equations:
.
.
.
.
.
Workshop 1: Nilpotent matrices
Use the nilpotent function defined in Section 4 to determine whether the following matrices are nilpotent and if so the degree.
Match the matrices to the following answers:
Nilpotent, degree 2
Nilpotent, degree 3
Nilpotent, degree 4
Nilpotent, degree 5
Matrix is not nilpotent
Workshop 2: Raising a matrix to a power
Write a function in R that takes as its inputs a matrix and a positive integer and returns .
Hence find the element (the entry of the third row and second column) of the matrix where
Workshop 3: Approximating a matrix exponential
The exponential of a square matrix is defined by the infinite series
where .
Using your function for finding matrix powers, combined with a for loop, approximate by computing
where is as defined in the previous question. Give the entry of to 3 decimal places.
[Recall that may be computed in R using factorial(n).]