rray_diag()
creates a matrix filled with x
on the diagonal. Use offset
to place x
along an offset from the diagonal.
rray_diag(x, offset = 0)
x | A vector, matrix, array or rray. |
---|---|
offset | A single integer specifying the offset from the diagonal to
place |
A matrix, with x
on the diagonal.
No dimension names will be on the result.
# Creates a diagonal matrix rray_diag(1:5)#> [,1] [,2] [,3] [,4] [,5] #> [1,] 1 0 0 0 0 #> [2,] 0 2 0 0 0 #> [3,] 0 0 3 0 0 #> [4,] 0 0 0 4 0 #> [5,] 0 0 0 0 5# Offset `1:5` by 1 rray_diag(1:5, 1)#> [,1] [,2] [,3] [,4] [,5] [,6] #> [1,] 0 1 0 0 0 0 #> [2,] 0 0 2 0 0 0 #> [3,] 0 0 0 3 0 0 #> [4,] 0 0 0 0 4 0 #> [5,] 0 0 0 0 0 5 #> [6,] 0 0 0 0 0 0# You can also go the other way rray_diag(1:5, -1)#> [,1] [,2] [,3] [,4] [,5] [,6] #> [1,] 0 0 0 0 0 0 #> [2,] 1 0 0 0 0 0 #> [3,] 0 2 0 0 0 0 #> [4,] 0 0 3 0 0 0 #> [5,] 0 0 0 4 0 0 #> [6,] 0 0 0 0 5 0#> [,1] [,2] [,3] [,4] [,5] #> [1,] 1 0 0 0 0 #> [2,] 0 1 0 0 0 #> [3,] 0 0 1 0 0 #> [4,] 0 0 0 1 0 #> [5,] 0 0 0 0 1# One interesting use case of this is to create # a square empty matrix with dimensions (offset, offset) rray_diag(rray(integer()), 3)#> <rray<int>[,3][3]> #> [,1] [,2] [,3] #> [1,] 0 0 0 #> [2,] 0 0 0 #> [3,] 0 0 0#> [,1] [,2] [,3] #> [1,] FALSE FALSE FALSE #> [2,] FALSE FALSE FALSE #> [3,] FALSE FALSE FALSE