diag
diag(x)
diag(x, k)
Create a diagonal matrix or retrieve the diagonal of a matrix. When x is a vector, a matrix with the vector values on the diagonal will be returned. When x is a matrix, a vector with the diagonal values of the matrix is returned. When k is provided, the k-th diagonal will be filled in or retrieved, if k is positive, the values are placed on the super diagonal. When k is negative, the values are placed on the sub diagonal.
Try it yourself:
$1 | diag(1:3)
| |
$2 | diag(1:3, 1)
| |
$3 | a = [1, 2, 3; 4, 5, 6; 7, 8, 9]
| |
$4 | diag(a)
|