简体   繁体   中英

Concatenate torch tensor at a certain index

I am looking to Concatenate 2 torch tensors at a certain index. As an example, I want to add b after a[1].

a = torch.Tensor([1, 2, 3, 4, 5])
b = torch.Tensor([6, 7, 8, 9, 10])

The desired output is

torch.Tensor([1, 2, 6, 7, 8, 9, 10, 3, 4, 5])

I tried torch.cat , but I can only have

tensor([ 6.,  7.,  8.,  9., 10.,  1.,  2.,  3.,  4.,  5.])
tensor([ 1.,  2.,  3.,  4.,  5.,  6.,  7.,  8.,  9., 10.])

you will need to split the first tensor and concatenate the second in between

torch.cat([a[:2], b, a[2:]])

output will be like

tensor([ 1.,  2.,  6.,  7.,  8.,  9., 10.,  3.,  4.,  5.])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM