# diagonal¶

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

This OP 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

print(x)
# Tensor(shape=[2, 2, 3], dtype=float32, place=CUDAPlace(0), stop_gradient=True,
#        [[[0.45661032, 0.03751532, 0.90191704],
#          [0.43760979, 0.86177313, 0.65221709]],

#         [[0.17020577, 0.00259554, 0.28954273],
#          [0.51795638, 0.27325270, 0.18117726]]])

print(out1)
#       [[0.45661032, 0.51795638],
#        [0.03751532, 0.27325270],
#        [0.90191704, 0.18117726]])

out2 = paddle.diagonal(x, offset=0, axis1=2, axis2=1)
print(out2)
#       [[0.45661032, 0.86177313],
#        [0.17020577, 0.27325270]])

out3 = paddle.diagonal(x, offset=1, axis1=0, axis2=1)
print(out3)
#       [[0.43760979],
#        [0.86177313],
#        [0.65221709]])

out4 = paddle.diagonal(x, offset=0, axis1=1, axis2=2)
print(out4)