UNPKG

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