Pytorch Torch Diagflat
# PyTorch torch.diagflat Function
* * Pytorch torch Reference Manual](#)
`torch.diagflat` is a function in PyTorch used to create a diagonal flattened matrix. Whether the input is one-dimensional or multi-dimensional, it will be flattened and used as diagonal elements.
### Function Definition
torch.diagflat(input, diagonal=0)
Parameter Description:
* `input`: Input tensor, will be flattened
* `diagonal`: Diagonal index
* * *
## Usage Examples
## Example
import torch
# Create 1D Tensor
x = torch.tensor([1,2,3])
# Create a diagonal flat matrix
y = torch.diagflat(x)
print(y)
The output result is:
tensor([[1, 0, 0], [0, 2, 0], [0, 0, 3]])
## Example
import torch
# Create a 2D tensor
x = torch.tensor([[1,2],[3,4]])
# will be flattened to [1,2,3,4]οΌCreate a 4x4 diagonal matrix
y = torch.diagflat(x)
print(y)
The output result is:
tensor([[1, 0, 0, 0], [0, 2, 0, 0], [0, 0, 3, 0], [0, 0, 0, 4]])
* * Pytorch torch Reference Manual](#)
YouTip