mindspore.ops.diagonal

View Source On Gitee
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 input 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. In this case, remove the dim1 and dim2 dimensions of input and insert the last dimension of input by the diagonal elements determined by dim1 and dim2.

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. Default: 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). Default: 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). Default: 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
  • TypeError – if dim1 or dim2 are not an int.

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

Supported Platforms:

Ascend GPU CPU

Examples

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