.diagonal_scatter()
Anonymous contributor
Published Jan 23, 2025
Contribute to Docs
In PyTorch, the .diagonal_scatter()
function scatters all values from the source tensor into the specified diagonal of the input tensor.
Syntax
torch.diagonal_scatter(input, src, offset=0, dim1=0, dim2=1)
input
: The input tensor that serves as the base tensor where values fromsrc
will be scattered into the specified diagonal.src
: The source tensor containing the values to be inserted.offset
(Optional): Specifies which diagonal to modify.offset = 0
(default): The main diagonal.offset > 0
: Diagonals above the main diagonal.offset < 0
: Diagonals below the main diagonal.
dim1
(Optional): The first dimension along which the values are to be inserted. The default value is0
.dim2
(Optional): The second dimension along which the values are to be inserted. The default value is1
.
Example
The following example demonstrates the usage of the .diagonal_scatter()
function:
import torch# Create a 3x3 input tensor with all elements set to '0'input = torch.zeros(3, 3)# Create a source tensor containing the valuessrc = torch.tensor([1, 2, 3])# Insert the values along the main diagonal in 'input'res = torch.diagonal_scatter(input, src, 0)# Print the resultant tensorprint(res)
The above code produces the following output:
tensor([[1., 0., 0.],[0., 2., 0.],[0., 0., 3.]])
All contributors
- Anonymous contributor
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn PyTorch on Codecademy
- Career path
Data Scientist: Machine Learning Specialist
Machine Learning Data Scientists solve problems at scale, make predictions, find patterns, and more! They use Python, SQL, and algorithms.Includes 27 CoursesWith Professional CertificationBeginner Friendly90 hours - Free course
Intro to PyTorch and Neural Networks
Learn how to use PyTorch to build, train, and test artificial neural networks in this course.Intermediate3 hours