diagflat

paddle. diagflat ( x, offset=0, name=None ) [source]

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

If x is a tensor (more than 1-D), a 2-D square tensor with the elements of flattened x as the diagonal is returned.

The argument offset controls the diagonal offset.

If offset = 0, it is the main diagonal.

If offset > 0, it is superdiagonal.

If offset < 0, it is subdiagonal.

Parameters
  • x (Tensor) – The input tensor. It can be any shape. Its data type should be float16, float32, float64, int32, int64.

  • offset (int, optional) – The diagonal offset. A positive value represents superdiagonal, 0 represents the main diagonal, and a negative value represents subdiagonal. Default: 0 (main diagonal).

  • name (str, optional) – For details, please refer to Name. Generally, no setting is required. Default: None.

Returns

Tensor, a square matrix. The output data type is the same as input data type.

Examples

import paddle

x = paddle.to_tensor([1, 2, 3])
y = paddle.diagflat(x)
print(y)
# Tensor(shape=[3, 3], dtype=int64, place=Place(cpu), stop_gradient=True,
#        [[1, 0, 0],
#         [0, 2, 0],
#         [0, 0, 3]])

y = paddle.diagflat(x, offset=1)
print(y)
# Tensor(shape=[4, 4], dtype=int64, place=Place(cpu), stop_gradient=True,
#        [[0, 1, 0, 0],
#         [0, 0, 2, 0],
#         [0, 0, 0, 3],
#         [0, 0, 0, 0]])

y = paddle.diagflat(x, offset=-1)
print(y)
# Tensor(shape=[4, 4], dtype=int64, place=Place(cpu), stop_gradient=True,
#        [[0, 0, 0, 0],
#         [1, 0, 0, 0],
#         [0, 2, 0, 0],
#         [0, 0, 3, 0]])
import paddle

x = paddle.to_tensor([[1, 2], [3, 4]])
y = paddle.diagflat(x)
print(y)
# Tensor(shape=[4, 4], dtype=int64, place=Place(cpu), stop_gradient=True,
#        [[1, 0, 0, 0],
#         [0, 2, 0, 0],
#         [0, 0, 3, 0],
#         [0, 0, 0, 4]])

y = paddle.diagflat(x, offset=1)
print(y)
# Tensor(shape=[5, 5], dtype=int64, place=Place(cpu), stop_gradient=True,
#        [[0, 1, 0, 0, 0],
#         [0, 0, 2, 0, 0],
#         [0, 0, 0, 3, 0],
#         [0, 0, 0, 0, 4],
#         [0, 0, 0, 0, 0]])

y = paddle.diagflat(x, offset=-1)
print(y)
# Tensor(shape=[5, 5], dtype=int64, place=Place(cpu), stop_gradient=True,
#        [[0, 0, 0, 0, 0],
#         [1, 0, 0, 0, 0],
#         [0, 2, 0, 0, 0],
#         [0, 0, 3, 0, 0],
#         [0, 0, 0, 4, 0]])