Index assignment in c++

x, x2 = torch.rand(2, 10), torch.rand(2, 3)
ind = torch.tensor([1,3,7], dtype=torch.long)
x[:, ind] = x2

could anyone tell me how to do last assignment in c++?
I tried

x.index_select(x, 1, ind) = x2

but it does not work.

Documents here Tensor Indexing API — PyTorch master documentation

I think the correct way should be

// make sure ind is torch::Tensor
x.index_put_({torch::indexing::Slice(1), ind} = x2
1 Like

the exact correct way is

x.index_put_({torch::indexing::Slice(), ind}, x2)

Thanks for letting me know torch::indexing apis.

The direct way to make the initial code work is to use copy_ to a view.

x.index_select(1, ind).copy_(x2)

This works in both Python and C++ (but I think sometimes you used to need to assign the view to a Tensor to make it work).

I just tested. x.index_select(1, ind).copy_(x2) does not work. I think x.index_select(1, ind) created a temporary tensor.

1 Like

Oh right. That only works with .select not indexing with multiple indices, sorry.