diag.md (1610B)
1 <!-- Note: This file is automatically generated from source code comments. Changes made in this file will be overridden. --> 2 3 # Function diag 4 5 Create a diagonal matrix or retrieve the diagonal of a matrix 6 7 When `x` is a vector, a matrix with vector `x` on the diagonal will be returned. 8 When `x` is a two dimensional matrix, the matrixes `k`th diagonal will be returned as vector. 9 When k is positive, the values are placed on the super diagonal. 10 When k is negative, the values are placed on the sub diagonal. 11 12 13 ## Syntax 14 15 ```js 16 math.diag(X) 17 math.diag(X, format) 18 math.diag(X, k) 19 math.diag(X, k, format) 20 ``` 21 22 ### Parameters 23 24 Parameter | Type | Description 25 --------- | ---- | ----------- 26 `x` | Matrix | Array | A two dimensional matrix or a vector 27 `k` | number | BigNumber | The diagonal where the vector will be filled in or retrieved. Default value: 0. 28 `format` | string | The matrix storage format. Default value: 'dense'. 29 30 ### Returns 31 32 Type | Description 33 ---- | ----------- 34 Matrix | Array | Diagonal matrix from input vector, or diagonal from input matrix. 35 36 37 ### Throws 38 39 Type | Description 40 ---- | ----------- 41 42 43 ## Examples 44 45 ```js 46 // create a diagonal matrix 47 math.diag([1, 2, 3]) // returns [[1, 0, 0], [0, 2, 0], [0, 0, 3]] 48 math.diag([1, 2, 3], 1) // returns [[0, 1, 0, 0], [0, 0, 2, 0], [0, 0, 0, 3]] 49 math.diag([1, 2, 3], -1) // returns [[0, 0, 0], [1, 0, 0], [0, 2, 0], [0, 0, 3]] 50 51 // retrieve the diagonal from a matrix 52 const a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] 53 math.diag(a) // returns [1, 5, 9] 54 ``` 55 56 57 ## See also 58 59 [ones](ones.md), 60 [zeros](zeros.md), 61 [identity](identity.md)