mindspore.ops.diagonal

mindspore.ops.diagonal(input, offset=0, dim1=0, dim2=1)[source]

Returns specified diagonals of input.

If input is 2-D, returns the diagonal of input with the given offset. If a has more than two dimensions, then the axes specified by dim1 and dim2 are used to determine the 2-D sub-array whose diagonal is returned. The shape of the resulting array can be determined by removing dim1 and dim2 and appending an index to the right equal to the size of the resulting diagonals.

Parameters
  • input (Tensor) – Array from which the diagonals are taken.

  • offset (int, optional) – Offset of the diagonal from the main diagonal. Can be positive or negative. Defaults: 0.

  • dim1 (int, optional) – Axis to be used as the first axis of the 2-D sub-arrays from which the diagonals should be taken. Defaults to first axis (0).

  • dim2 (int, optional) – Axis to be used as the second axis of the 2-D sub-arrays from which the diagonals should be taken. Defaults to second axis (1).

Returns

Tensor, if input is 2-D, then input 1-D array containing the diagonal. If input.ndim > 2, then the dimensions specified by dim1 and dim2 are removed, and a new axis inserted at the end corresponding to the diagonal.

Raises

ValueError – if the input tensor has less than two dimensions.

Supported Platforms:

Ascend GPU CPU

Examples

>>> x = Tensor([[0, 1], [2, 3]], mstype.float32)
>>> output = ops.diagonal(x)
>>> print(output)
[0 3]