# In Pytorch, if I have a 2D tensor, how to iterate over this tensor to get every value changed

I have a 2d Tensor, whose size is 1024x1024 and the values in the tensor is 0.3333, 0.6667, and 1.0000, so I would like to change all these values to 0,1,2.

Could some one tell me how to iterate over this tensor.

• Hi, I just do a trick, torch.round(tensor_a / 0.3).long()-1 Jan 29 '19 at 6:18

Consider the original tensor is $$x$$.

x = torch.tensor([[0.3333, 0.6667, 1.0000], [1.0000, 0.6667, 0.3333]])


produces

x

tensor([[ 0.3333,  0.6667,  1.0000],
[ 1.0000,  0.6667,  0.3333]])


We can do a broadcasting and then cast it to an integer tensor

y = (3 * x - 1).int()
y

tensor([[ 0,  1,  2],
[ 2,  1,  0]], dtype=torch.int32

)


t1 = torch.tensor([[0.33, 1.], [0.66, 1.]])