Table Of Contents
Table Of Contents

diag

mxnet.ndarray.diag(data=None, k=_Null, out=None, name=None, **kwargs)

Extracts a diagonal or constructs a diagonal array.

diag’s behavior depends on the input array dimensions:

  • 1-D arrays: constructs a 2-D array with the input as its diagonal, all other elements are zero
  • 2-D arrays: returns elements in the diagonal as a new 1-D array
  • N-D arrays: not supported yet

Examples:

x = [[1, 2, 3],
     [4, 5, 6]]

diag(x) = [1, 5]

diag(x, k=1) = [2, 6]

diag(x, k=-1) = [4]

x = [1, 2, 3]

diag(x) = [[1, 0, 0],
           [0, 2, 0],
           [0, 0, 3]]

diag(x, k=1) = [[0, 1, 0],
                [0, 0, 2],
                [0, 0, 0]]

diag(x, k=-1) = [[0, 0, 0],
                 [1, 0, 0],
                 [0, 2, 0]]

Defined in src/operator/tensor/diag_op.cc:L68

Parameters:
  • data (NDArray) – Input ndarray
  • k (int or None, optional, default='0') – Diagonal in question. The default is 0. Use k>0 for diagonals above the main diagonal, and k<0 for diagonals below the main diagonal. If input has shape (S0 S1) k must be between -S0 and S1
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays