Functions to extract or replace the diagonals of an array, or construct a diagonal array.

diagonal(x = 1, dim = rep(2, 2))

diagonal(x) <- value

Arguments

x

an array from which to extract the diagonals, or a vector giving the diagonal values to construct the array.

dim

the dimensions of the (square) array to construct when x is a vector.

value

vector giving the values of the diagonal entries.

Value

Vector of the diagonal entries of x if x is an array. If x is a vector, returns the diagonal array with the entries given by x.

Functions

  • diagonal(x) <- value: set diagonals.

References

Guidotti E (2022). "calculus: High-Dimensional Numerical and Symbolic Calculus in R." Journal of Statistical Software, 104(5), 1-37. doi:10.18637/jss.v104.i05

See also

Other tensor algebra: contraction(), delta(), einstein(), epsilon(), index()

Examples

### 3x3 matrix
diagonal(x = 1, dim = c(3,3))
#>      [,1] [,2] [,3]
#> [1,]    1    0    0
#> [2,]    0    1    0
#> [3,]    0    0    1

### 2x2x2 array
diagonal(x = 1:2, dim = c(2,2,2))
#> , , 1
#> 
#>      [,1] [,2]
#> [1,]    1    0
#> [2,]    0    0
#> 
#> , , 2
#> 
#>      [,1] [,2]
#> [1,]    0    0
#> [2,]    0    2
#> 

### extract diagonals 
x <- diagonal(1:5, dim = c(5,5,5))
diagonal(x)
#> [1] 1 2 3 4 5

### set diagonals
x <- array(0, dim = c(2,2,2))
diagonal(x) <- 1:2
x
#> , , 1
#> 
#>      [,1] [,2]
#> [1,]    1    0
#> [2,]    0    0
#> 
#> , , 2
#> 
#>      [,1] [,2]
#> [1,]    0    0
#> [2,]    0    2
#>