Diagonal matrix or vector with offset
stm_diag.Rd
stm_diag()
extracts the diagonal elements of a matrix or vector,
allowing for an optional offset, and returns the result as a matrix or
vector.
Arguments
- vmat
A vector or matrix from which the diagonal is extracted. If a matrix, the function extracts the diagonal elements, with an optional offset
k
.- k
Optional. An integer specifying the diagonal offset. The default is
0
for the main diagonal. A positive value retrieves diagonals above the main diagonal, while a negative value retrieves diagonals below the main diagonal.
Value
A vector or matrix with the extracted diagonal elements, or an empty numeric vector if no elements are present.
Details
The function extracts the diagonal elements of the input vmat
with
an optional offset. The offset k
shifts the diagonal. If k
is positive, it retrieves diagonals above the main diagonal; if negative,
it retrieves diagonals below the main diagonal. If vmat
is a matrix,
the output is a matrix; if it is a vector, the result is a vector.
Examples
A <- matrix(1:12, nrow = 3, byrow = TRUE)
print(A)
#> [,1] [,2] [,3] [,4]
#> [1,] 1 2 3 4
#> [2,] 5 6 7 8
#> [3,] 9 10 11 12
stm_diag(A)
#> [1] 1 6 11
stm_diag(vmat = c(1, 2, 3))
#> [,1] [,2] [,3]
#> [1,] 1 0 0
#> [2,] 0 2 0
#> [3,] 0 0 3
stm_diag(vmat = c(1, 2, 3), k = 2)
#> [,1] [,2] [,3] [,4] [,5]
#> [1,] 0 0 1 0 0
#> [2,] 0 0 0 2 0
#> [3,] 0 0 0 0 3
#> [4,] 0 0 0 0 0
#> [5,] 0 0 0 0 0
stm_diag(vmat = c(1, 2, 3), k = -1)
#> [,1] [,2] [,3] [,4]
#> [1,] 0 0 0 0
#> [2,] 1 0 0 0
#> [3,] 0 2 0 0
#> [4,] 0 0 3 0