How to resize a tensor?

Lets say, I have a tensor
a = torch.tensor([[0.1, 1.2], [2.2, 3.1], [4.9, 5.2]])
the size of it is torch.Size([3, 2])

I want to resize it to torch.Size([3, 3]) by adding a 0 to each row. Like this,
torch.tensor([[0.1, 1.2, 0], [2.2, 3.1, 0], [4.9, 5.2, 0]])

How can I resize and add a 0?

Does simply allocating a new tensor work?

>>> a = torch.tensor([[0.1, 1.2], [2.2, 3.1], [4.9, 5.2]])
>>> b = torch.zeros([3, 3])
>>> b[:3, :2] = a
>>> b
tensor([[0.1000, 1.2000, 0.0000],
        [2.2000, 3.1000, 0.0000],
        [4.9000, 5.2000, 0.0000]])

My suspicion is that even if a native “resize” function were available the implementation would essentially do the same thing here.

1 Like