# tensorplay.functional.diag Source: https://www.tensorplay.cn/docs/generated/tensorplay.functional.diag.html ```python tensorplay.functional.diag(input, diagonal=0, *, out=None) → 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](/docs/generated/tensorplay.functional.diagonal.html#tensorplay.functional.diagonal) controls which diagonal to consider: - If [diagonal](/docs/generated/tensorplay.functional.diagonal.html#tensorplay.functional.diagonal) = 0, it is the main diagonal. - If [diagonal](/docs/generated/tensorplay.functional.diagonal.html#tensorplay.functional.diagonal) > 0, it is above the main diagonal. - If [diagonal](/docs/generated/tensorplay.functional.diagonal.html#tensorplay.functional.diagonal) Parameters: - input ([Tensor](/docs/generated/tensorplay.Tensor.html#tensorplay.Tensor)) – the input tensor. - diagonal ([int](https://docs.python.org/3/builtins/functions.html#int), optional) – the diagonal to consider Keyword Arguments: out ([Tensor](/docs/generated/tensorplay.Tensor.html#tensorplay.Tensor), optional) – the output tensor. > **See also** > > tensorplay.diagonal() always returns the diagonal of its input. tensorplay.diagflat() always constructs a tensor with diagonal elements specified by the input. Examples: Get the square matrix where the input vector is the diagonal: ``` >>> a = tensorplay.randn(3) >>> a tensor([ 0.5950,-0.0872, 2.3298]) >>> tensorplay.diag(a) tensor([[ 0.5950, 0.0000, 0.0000], [ 0.0000,-0.0872, 0.0000], [ 0.0000, 0.0000, 2.3298]]) >>> tensorplay.diag(a, 1) tensor([[ 0.0000, 0.5950, 0.0000, 0.0000], [ 0.0000, 0.0000,-0.0872, 0.0000], [ 0.0000, 0.0000, 0.0000, 2.3298], [ 0.0000, 0.0000, 0.0000, 0.0000]]) ``` Get the k-th diagonal of a given matrix: ``` >>> a = tensorplay.randn(3, 3) >>> a tensor([[-0.4264, 0.0255,-0.1064], [ 0.8795,-0.2429, 0.1374], [ 0.1029,-0.6482,-1.6300]]) >>> tensorplay.diag(a, 0) tensor([-0.4264,-0.2429,-1.6300]) >>> tensorplay.diag(a, 1) tensor([ 0.0255, 0.1374]) ```