I have a 1D tensor s
with elements in ascending order. I want to generate a 2D tensor a
of shape (len(s)-1, s[-1])
such that its elements [i, s[i]:s[i+1]]
are 1
, all other elements being 0
. How can I do this vectorially without using loops?
Example:
Input: s = torch.tensor([0,2,5,7])
Output:
a = torch.tensor([
[1,1,0,0,0,0,0],
[0,0,1,1,1,0,0],
[0,0,0,0,0,1,1]
])
Loop implementation:
a = torch.zeros(len(s)-1,s[-1])
for i in range(len(a)):
a[i, s[i]:s[i+1]] = 1
This is part of training a neural network, so I’m looking for a vector implementation.