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
diag(X)
diag(X, format)
diag(X, k)
diag(X, k, format)
Parameters
Parameter | Type | Description |
---|---|---|
x |
Matrix | Array | A two dimensional matrix or a vector |
k |
number | 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 | Array | Diagonal matrix from input vector, or diagonal from input matrix. |
Examples
// create a diagonal matrix
diag([1, 2, 3]); // returns [[1, 0, 0], [0, 2, 0], [0, 0, 3]]
diag([1, 2, 3], 1); // returns [[0, 1, 0, 0], [0, 0, 2, 0], [0, 0, 0, 3]]
diag([1, 2, 3], -1); // returns [[0, 0, 0], [1, 0, 0], [0, 2, 0], [0, 0, 3]]
// retrieve the diagonal from a matrix
var a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
diag(a); // returns [1, 5, 9]