Reputation: 261
I am new to torch7, and I can't find a way to get the some non contiguous indices of a tensor based on another tensor. In numpy, what I do is the following:
array = np.zeros(5) # array = [0 0 0 0 0]
indices = np.array([0, 2, 4])
array[indices] = np.array([1, 2, 3]) # array = [1 0 2 0 3]
Is there a way to do something similar in torch7? Something like:
array = torch.zeros(5) -- array = [0 0 0 0 0]
indices = torch.Tensor({1, 3, 5})
array[indices] = torch.Tensor({1, 2, 3}) -- array = [1 0 2 0 3]
Thanks!
Upvotes: 2
Views: 190
Reputation: 164
If you are a python user, maybe you could also try https://github.com/imodpasteur/lutorpy . For example, you can process your array in python and then convert it to torch tensor. If you want to convert back to numpy array, the conversion is instant because it only pass the pointer, and two object in python and lua are sharing the same memory.
array = np.zeros(5) # array = [0 0 0 0 0]
indices = np.array([0, 2, 4])
array[indices] = np.array([1, 2, 3]) # array = [1 0 2 0 3]
require("torch")
# convert numpy array to torch tensor
tensor = torch.fromNumpyArray(array)
# put your torch code here
#convert back to numpy array
array = tensor.asNumpyArray()
# now array is sharing memory with tensor
Upvotes: 0
Reputation: 2160
torch.IndexCopy
does exactly what you need:
array:indexCopy(1, indices, torch.Tensor({1, 2, 3}))
Upvotes: 1
Reputation: 261
Ok, looking arround, I couldn't find an exact solution, but I found an approximation of what I wanted to do, I share it in case someone else finds it useful:
array = torch.zeros(5) -- array = [0 0 0 0 0]
indices = torch.LongTensor({1, 3, 5}) -- Is important that this is a LongTensor
array:indexAdd(1, indices, torch.Tensor({1, 2, 3})) -- array = [1 0 2 0 3]
Upvotes: 1