<!-- Note: This file is automatically generated from source code comments. Changes made in this file will be overridden. -->

# 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

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

### Parameters

Parameter | Type | Description
--------- | ---- | -----------
`x` | Matrix &#124; Array | A two dimensional matrix or a vector
`k` | number &#124; 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 &#124; Array | Diagonal matrix from input vector, or diagonal from input matrix.


## Examples

```js
 // 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]
```


## See also

[ones](ones.md),
[zeros](zeros.md),
[identity](identity.md)
