calculus (version 0.1.0)

trace: Tensor Contraction

Description

Sums over repeated indices in a tensor. Can be seen as a generalization of the trace.

Usage

trace(x, i = NULL, drop = TRUE)

Arguments

x

array.

i

subset of repeated indices to sum up. If NULL, the tensor contraction takes place on all repeated indices of x.

drop

logical. Drop summation indices? If FALSE, keep dummy dimensions.

Value

array.

See Also

index, einstein

Examples

Run this code
# 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