函数 diag #
创建对角矩阵或检索矩阵的对角线
当 x 是一个向量时,将返回一个以向量 x 为对角线的矩阵。当 x 是一个二维矩阵时,将以向量形式返回矩阵的 k 次对角线。当 k 为正数时,值放置在超对角线上。当 k 为负数时,值放置在次对角线上。
Syntax #
math.diag(X)
math.diag(X, format)
math.diag(X, k)
math.diag(X, k, format)
Parameters #
| Parameter | Type | Description |
|---|---|---|
x |
矩阵 | 数组 | 二维矩阵或向量 |
k |
number | BigNumber | 将填充向量或检索对角线的对角线。默认值:0。 |
format |
string | 矩阵存储格式。默认值:“dense”。 |
Returns #
| Type | Description |
|---|---|
| 矩阵 | 数组 | 来自输入向量的对角矩阵,或来自输入矩阵的对角线。 |
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]