diag

Syntax

diag(X)

Details

  • If X is a vector, return a diagonal matrix.
  • If X is a square matrix, return a vector with the diagonal elements of the matrix.

DolphinDB’s diag function and NumPy’s numpy.diag function are similar in their core functionality, but differ in parameter design, functional scope, and handling of missing values.

  • DolphinDB’s diag function accepts only a single argument, does not support diagonal offsets, operates only on the main diagonal, and requires the input to be either a vector or a square matrix.
  • numpy.diag supports an optional offset parameter, allowing extraction or construction of arbitrary diagonals, and accepts one-dimensional or two-dimensional arrays as input.
  • In terms of missing value handling, DolphinDB’s diag treats NULL values as 0, whereas numpy.diag preserves NaN/Inf values as-is.

Parameters

X is a numeric vector or a square matrix.

Examples

diag(1..5);
#0 #1 #2 #3 #4
1 0 0 0 0
0 2 0 0 0
0 0 3 0 0
0 0 0 4 0
0 0 0 0 5
m=1..4$2:2;
m;
#0 #1
1 3
2 4
diag(m);
// output: [1,4]