1 |
|
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 | ## 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
|
46 | const a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
|
47 | math.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)
|