diagonal

paddle. diagonal ( x, offset=0, axis1=0, axis2=1, name=None ) [source]

Computes the diagonals of the input tensor x.

If x is 2D, returns the diagonal. If x has larger dimensions, diagonals be taken from the 2D planes specified by axis1 and axis2. By default, the 2D planes formed by the first and second axis of the input tensor x.

The argument offset determines where diagonals are taken from input tensor x:

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

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

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

Parameters
  • x (Tensor) – The input tensor x. Must be at least 2-dimensional. The input data type should be bool, int32, int64, float16, float32, float64.

  • offset (int, optional) – Which diagonals in input tensor x will be taken. Default: 0 (main diagonals).

  • axis1 (int, optional) – The first axis with respect to take diagonal. Default: 0.

  • axis2 (int, optional) – The second axis with respect to take diagonal. Default: 1.

  • name (str, optional) – Name for the operation (optional, default is None). For more information, please refer to Name.

Returns

a partial view of input tensor in specify two dimensions, the output data type is the same as input data type.

Return type

Tensor

Examples

>>> import paddle

>>> paddle.seed(2023)
>>> x = paddle.rand([2, 2, 3],'float32')
>>> print(x)
Tensor(shape=[2, 2, 3], dtype=float32, place=Place(cpu), stop_gradient=True,
[[[0.86583614, 0.52014720, 0.25960937],
  [0.90525323, 0.42400089, 0.40641287]],
 [[0.97020894, 0.74437362, 0.51785129],
  [0.73292869, 0.97786582, 0.04315904]]])

>>> out1 = paddle.diagonal(x)
>>> print(out1)
Tensor(shape=[3, 2], dtype=float32, place=Place(cpu), stop_gradient=True,
[[0.86583614, 0.73292869],
 [0.52014720, 0.97786582],
 [0.25960937, 0.04315904]])

>>> out2 = paddle.diagonal(x, offset=0, axis1=2, axis2=1)
>>> print(out2)
Tensor(shape=[2, 2], dtype=float32, place=Place(cpu), stop_gradient=True,
[[0.86583614, 0.42400089],
 [0.97020894, 0.97786582]])

>>> out3 = paddle.diagonal(x, offset=1, axis1=0, axis2=1)
>>> print(out3)
Tensor(shape=[3, 1], dtype=float32, place=Place(cpu), stop_gradient=True,
[[0.90525323],
 [0.42400089],
 [0.40641287]])

>>> out4 = paddle.diagonal(x, offset=0, axis1=1, axis2=2)
>>> print(out4)
Tensor(shape=[2, 2], dtype=float32, place=Place(cpu), stop_gradient=True,
[[0.86583614, 0.42400089],
 [0.97020894, 0.97786582]])