Skip to content

Instantly share code, notes, and snippets.

@aschleg
Created October 7, 2016 13:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aschleg/cd500758cb9240ed635ac9cfc2cf3f59 to your computer and use it in GitHub Desktop.
Save aschleg/cd500758cb9240ed635ac9cfc2cf3f59 to your computer and use it in GitHub Desktop.
Simple function for computing the trace of a square matrix. Should replicate the output of sum(diag(matrix)).
# Simple function for computing the trace of a matrix. Should replicate the output of sum(diag(matrix)).
# Function requires a square n x n matrix as input.
# Used in post demonstrating the trace of a matrix here: http://wp.me/p4aZEo-5Nb
trace <- function(A) {
n <- dim(A)[1] # get dimension of matrix
# Check that the matrix is square
if (n != dim(A)[2]) {
stop('Matrix is not square')
}
tr <- 0 # initialize trace value
# Loop over the diagonal elements of the supplied matrix and add the element to tr
for (k in 1:n) {
l <- A[k,k]
tr <- tr + l
}
return(tr[[1]])
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment