3

Suppose I have a list of indices and wish to modify an existing array with this list. Currently the only way I can do this is by using a for loop as follows. Just wondering if there is a faster/ efficient way.

torch.manual_seed(0)
a = torch.randn(5,3)
idx = torch.Tensor([[1,2], [3,2]], dtype=torch.long)
for i,j in idx:
    a[i,j] = 1

I initially assumed that gather or index_select would go some way in answering this question, but looking at documentation this doesn't seem to be the answer.

In my particular case, a is a 5 dimensional vector and idx is a Nx5 vector. So the output (after subscripting with something like a[idx]) I'd expect is a (N,) shaped vector.

Answer

Thanks to @shai below, the answer that I was seeking was: a[idx.t().chunk(chunks=2,dim=0)]. Taken from this SO answer.

1 Answer 1

1

It's quite simple

a[idx[:,0], idx[:,1]] = 1

You can find a more general solution in this thread.

Sign up to request clarification or add additional context in comments.

2 Comments

Would this scale even if say a had 5 dimensions. Will wait to see if there is a more general answer before accepting. Sorry for adding the additional requirement late.
@sachinruk please see the added link.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.