# Function diag #

Create a diagonal matrix or retrieve the diagonal of a matrix

When `x` is a vector, a matrix with vector `x` on the diagonal will be returned. When `x` is a two dimensional matrix, the matrixes `k`th diagonal will be returned as vector. When k is positive, the values are placed on the super diagonal. When k is negative, the values are placed on the sub diagonal.

## Syntax #

``````math.diag(X)
math.diag(X, format)
math.diag(X, k)
math.diag(X, k, format)
``````

### Parameters #

Parameter Type Description
`x` Matrix | Array A two dimensional matrix or a vector
`k` number | BigNumber The diagonal where the vector will be filled in or retrieved. Default value: 0.
`format` string The matrix storage format. Default value: ‘dense’.

### Returns #

Type Description
Matrix | Array Diagonal matrix from input vector, or diagonal from input matrix.

### Throws #

Type | Description —- | ———–

## Examples #

`````` // create a diagonal matrix
math.diag([1, 2, 3])      // returns [[1, 0, 0], [0, 2, 0], [0, 0, 3]]
math.diag([1, 2, 3], 1)   // returns [[0, 1, 0, 0], [0, 0, 2, 0], [0, 0, 0, 3]]
math.diag([1, 2, 3], -1)  // returns [[0, 0, 0], [1, 0, 0], [0, 2, 0], [0, 0, 3]]

// retrieve the diagonal from a matrix
const a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
math.diag(a)   // returns [1, 5, 9]
``````