mindspore.Tensor.diag

Tensor.diag() Tensor

For details, please refer to mindspore.ops.diag().

Tensor.diag(diagonal=0) Tensor

If input is a vector (1-D tensor), then returns a 2-D square tensor with the elements of input as the diagonal.

If input is a matrix (2-D tensor), then returns a 1-D tensor with the diagonal elements of input.

The argument diagonal controls which diagonal to consider:

  • If diagonal = 0, it is the main diagonal.

  • If diagonal > 0, it is above the main diagonal.

  • If diagonal < 0, it is below the main diagonal.

Warning

This is an experimental API that is subject to change or deletion.

Parameters

diagonal (int, optional) – the diagonal to consider. Default: 0.

Returns

  • If input shape is (x0): then output shape is (x0+|diagonal|,x0+|diagonal|) 2-D Tensor.

  • If input shape is (x0,x1): then output shape is main diagonal to move (|diagonal|) elements remains elements' length 1-D Tensor.

Return type

Tensor, has the same dtype as the input, its shape is up to diagonal

Raises

ValueError – If shape of input is not 1-D and 2-D.

Supported Platforms:

Ascend

Examples

>>> from mindspore import Tensor
>>> input = Tensor([1, 2, 3, 4]).astype('int32')
>>> output = input.diag()
>>> print(output)
[[1 0 0 0]
 [0 2 0 0]
 [0 0 3 0]
 [0 0 0 4]]