Generate diagonal matrices or return diagonal of a matrix

Diag(x, k = 0)

Arguments

x

vector or matrix

k

integer indicating a secondary diagonal

Details

If x is a vector, Diag(x, k) generates a matrix with x as the (k-th secondary) diagonal.

If x is a matrix, Diag(x, k) returns the (k-th secondary) diagonal of x.

The k-th secondary diagonal is above the main diagonal for k > 0 and below the main diagonal for k < 0.

Value

matrix or vector

Note

In Matlab/Octave this function is called diag() and has a different signature than the corresponding function in R.

See also

Examples

Diag(matrix(1:12,3,4),  1)
#> [1]  4  8 12
Diag(matrix(1:12,3,4), -1)
#> [1] 2 6

Diag(c(1,5,9), 1)
#>      [,1] [,2] [,3] [,4]
#> [1,]    0    1    0    0
#> [2,]    0    0    5    0
#> [3,]    0    0    0    9
#> [4,]    0    0    0    0
Diag(c(1,5,9), -1)
#>      [,1] [,2] [,3] [,4]
#> [1,]    0    0    0    0
#> [2,]    1    0    0    0
#> [3,]    0    5    0    0
#> [4,]    0    0    9    0