Diagonal Matrices

DESCRIPTION:

Either creates a diagonal matrix or extracts the diagonal elements of a matrix. The function diag is generic.

USAGE:

diag(x, ...)
diag.default(x = <<see below>>, nrow = <<see below>>,
             ncol=<<see below>>)
diag(x) <- value

OPTIONAL ARGUMENTS:

x
matrix or vector. Missing values ( NAs) are allowed.
nrow
number of rows of output matrix.
ncol
number of columns of output matrix.
value
vector whose length is the minimum of the number of rows and the number of columns. Missing values ( NAs) are allowed.

VALUE:

if x is a matrix, the vector of diagonal elements of x;

if x is a vector of length greater than one, a matrix with x on its diagonal and zeroes elsewhere.

if x is a vector of length 1 and both nrow and ncol are missing, the value is an x by x identity matrix. By default, the matrix is square with zeros off the diagonal, but it can be made rectangular by specifying nrow and ncol.

The diag(x) <- value form allows replacement of the values on the diagonal of a matrix.

DETAILS:

If x is missing, then nrow must be given and ncol equals nrow if it is also missing; in this case 1s are placed on the diagonal of the result.

SEE ALSO:

, , , .

EXAMPLES:

amat <- matrix(c(12,15,6,10,2,9), nrow = 2)
diag(amat)    # extract diagonal elements ((1,1),(2,2),etc.)
diag(diag(amat))   # create a square matrix with
                   # diagonal of amat
diag(5)   # 5 by 5 identity matrix
diag(nrow = 5) # same thing
diag(as.matrix(5)) # 5
diag(x, nrow = 2*length(x))  # replicate x on the diagonal of a matrix
diag(x, nrow = length(x))  # put x on the diagonal of a matrix
# works even if length(x) is 1 or x is a matrix
diag(x) <- diag(y)  # put diagonal of y into diagonal of x