Created
October 7, 2016 13:54
-
-
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)).
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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