Pad multiple torch tensor over the last dim

I have multiple torch tensors with the following shape
‘’’
x1 = torch.Size([1, 512, 177])
x2 = torch.Size([1, 512, 250])
x3 = torch.Size([1, 512, 313])
‘’’
How I can pad all these tensors by 0 over the last dimension, to have a unique shape like ([1, 512, 350]).

Thanks

Hi Mohamed!

Use torch.cat(). (Doing so will create new tensors, but you can’t
avoid that – pytorch can’t increase the size of a tensor without creating
a new tensor.)

Consider:

>>> import torch
>>> torch.__version__
'1.9.0'
>>> x1 = torch.ones (1, 512, 177)
>>> pad = 350
>>> x1_pad = torch.cat ((x1, torch.zeros (1, 512, pad - x1.shape[2])), 2)
>>> x1_pad.shape
torch.Size([1, 512, 350])

Best.

K. Frank