# NOT RUN {
# trace of numeric matrix
x <- matrix(1:4, nrow = 2)
trace(x)
# trace of character matrix
x <- matrix(letters[1:4], nrow = 2)
trace(x)
# trace of a tensor (sum over diagonals)
x <- array(1:27, dim = c(3,3,3))
trace(x)
# tensor contraction over repeated indices
x <- array(1:27, dim = c(3,3,3))
index(x) <- c('i','i','j')
trace(x)
# tensor contraction over specific indices only
x <- array(1:16, dim = c(2,2,2,2))
index(x) <- c('i','i','k','k')
trace(x, i = 'k')
# tensor contraction keeping dummy dimensions
x <- array(letters[1:16], dim = c(2,2,2,2))
index(x) <- c('i','i','k','k')
trace(x, drop = FALSE)
# }
Run the code above in your browser using DataCamp Workspace