Suppose I have a tensor a
and I want to fill the inner with all 1 like tensor b
print(a)
tensor([[0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
[0., 0., 1., 1., 1., 1., 1., 0., 0., 0.],
[0., 1., 0., 1., 1., 1., 1., 1., 0., 0.],
[0., 1., 0., 0., 1., 0., 0., 0., 1., 0.],
[0., 1., 0., 1., 0., 0., 0., 0., 1., 0.],
[0., 1., 0., 1., 0., 0., 0., 1., 0., 0.],
[0., 1., 0., 1., 0., 0., 0., 1., 0., 0.],
[0., 0., 1., 0., 0., 0., 0., 1., 0., 0.],
[0., 0., 0., 1., 1., 1., 1., 0., 0., 0.],
[0., 0., 0., 0., 0., 0., 0., 0., 0., 0.]])
print(b)
tensor([[0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
[0., 0., 1., 1., 1., 1., 1., 0., 0., 0.],
[0., 1., 1., 1., 1., 1., 1., 1., 0., 0.],
[0., 1., 1., 1., 1., 1., 1., 1., 1., 0.],
[0., 1., 1., 1., 1., 1., 1., 1., 1., 0.],
[0., 1., 1., 1., 1., 1., 1., 1., 0., 0.],
[0., 1., 1., 1., 1., 1., 1., 1., 0., 0.],
[0., 0., 1., 1., 1., 1., 1., 1., 0., 0.],
[0., 0., 0., 1., 1., 1., 1., 0., 0., 0.],
[0., 0., 0., 0., 0., 0., 0., 0., 0., 0.]])
I’m currently using the for
loop to do this, are there any ways to do this without using the for
loop? Thanks.
- Only using Pytorch
- The areas I want to fill always have contiguous boundaries.
-
for
loop below loops throughrow
first thencolumn
b = torch.zeros(a.shape)
for i in range(a.shape[0]):
occupied = torch.where(a[i] == 1)[0]
if len(occupied) > 0:
# indexes in occupied are in ascending order so value of any index
# between the first and last is filled with 1
for j in range(occupied[0], occupied[-1] + 1):
b[i][j] = 1