5

Assume that I have a list [(0,0),(1,0),(1,1)] and another list [4,5,6] and a matrix X with size is (3,2). I am trying to assign the list to the matrix like X[0,0] = 4, X[1,0] = 5 and X[1,1] = 6. But it seems like I have a problem of assigning a list to tensor

x = torch.zeros(3,2)
indices = [(0,0),(1,0),(1,1)]
value = [4,5,6]
x[indices] = values

Error:

TypeError                                 Traceback (most recent call last)
<ipython-input-7-dec4e6a479a5> in <module>
     
   4 indices = [(0, 0), (1, 0), (1, 1)]
 
   5 values = [4, 5, 6]

----> 6 x[indices] = values

TypeError: can't assign a list to a torch.FloatTensor

2 Answers 2

4

If you can make indices tensor than it would make indexing easy

indices = torch.tensor([(0,0),(1,0),(1,1)])

x[indices[:,0], indices[:,1]] = torch.tensor(values).float()
x
tensor([[4., 0.],
        [5., 6.],
        [0., 0.]])

As our x is float type we need to convert values to same.

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

Comments

2

In general, the answer to "how do I change a list to a Tensor" is to use torch.Tensor(list). But that will not solve your actual problem here.

One way would be to associate the index and value and then iterate over them:

for (i,v) in zip(indices,values) :
   x[i] = v

1 Comment

No problem! If you could accept the answer, I'd appreciate it.

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.