Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign a tensor to multiple slices

Let

a = tensor([[0, 0, 0, 0],
            [0, 0, 0, 0],
            [0, 0, 0, 0]])
b = torch.tensor([1, 2])
c = tensor([[1, 2, 0, 0],
            [0, 1, 2, 0],
            [0, 0, 1, 2]])

Is there a way to obtain c by assigning b to slices of a without any loops? That is, a[indices] = b for some indices or something similar?

like image 396
user76284 Avatar asked Jan 23 '26 07:01

user76284


1 Answers

You can use scatter method in pytorch.

a = torch.tensor([[0, 0, 0, 0],
                 [0, 0, 0, 0],
                 [0, 0, 0, 0]])

b = torch.tensor([1, 2])

index = torch.tensor([[0,1],[1,2],[2,3]])

a.scatter_(1, index, b.view(-1,2).repeat(3,1))
# tensor([[1, 2, 0, 0],
#         [0, 1, 2, 0],
#         [0, 0, 1, 2]])
like image 69
zihaozhihao Avatar answered Jan 24 '26 19:01

zihaozhihao