Tensor elements won't update in a loop

Hi experts. I cannot update tensors in loops over zipped and flattened pairs, and I am confused by this.

If I run

``````for x, y in zip(xx.flatten(), yy.flatten()):
t = torch.tensor([0, 0, 0, 0])
print(x,y)
t[1]=torch.tensor(x)
t[2]=torch.tensor(y)
print(t)
``````

The output is:

``````-0.05 -0.05
tensor([0, 0, 0, 0])
-0.03888888888888889 -0.05
tensor([0, 0, 0, 0])
-0.02777777777777778 -0.05
tensor([0, 0, 0, 0])
-0.01666666666666667 -0.05
tensor([0, 0, 0, 0])
...
...
``````

But if I access the elements individually, the tensor is changed. Or if I loop over

``````for x, y in zip( range(10), range(10)):
t = torch.tensor([0, 0, 0, 0])
print(x,y)
t[1]=torch.tensor(x)
t[2]=torch.tensor(y)
print(t)
``````

The output is:

``````0 0
tensor([0, 0, 0, 0])
1 1
tensor([0, 1, 1, 0])
2 2
tensor([0, 2, 2, 0])
3 3
tensor([0, 3, 3, 0])
4 4
tensor([0, 4, 4, 0])
...
...
``````

Is there something about flattening that would cause tensors to fail to update?

The xx, and yy are formed by mesh grid in case that helps:

`````` xx, yy = np.meshgrid(np.linspace(-0.05, 1.05, 100), np.linspace(-0.05, 1.05, 100))
``````

In the second case, it works because the elements you give to `t[1]` and `t[2]` are integers, and `t` is of type `torch.int64`.
In the first case, as `t` is of type `torch.int64`, only the integer parts of `x` and `y` are assigned to `t[1]` and `t[2]` respectively.

``````xx, yy = np.meshgrid(np.linspace(-0.05, 1.05, 2), np.linspace(-0.05, 1.05, 2))

for x, y in zip(xx.flatten(), yy.flatten()):
t = torch.tensor([0, 0, 0, 0])
print(x,y)
t[1]=torch.tensor(x)
t[2]=torch.tensor(y)
print(t)

"""
-0.05 -0.05
tensor([0, 0, 0, 0])
1.05 -0.05
tensor([0, 1, 0, 0])
-0.05 1.05
tensor([0, 0, 1, 0])
1.05 1.05
tensor([0, 1, 1, 0])
"""
``````

But :

``````xx, yy = np.meshgrid(np.linspace(-0.05, 1.05, 2), np.linspace(-0.05, 1.05, 2))

for x, y in zip(xx.flatten(), yy.flatten()):
t = torch.tensor([0, 0, 0, 0]).float()
#or t = torch.FloatTensor([0, 0, 0, 0])
print(x,y)
t[1]=torch.tensor(x)
t[2]=torch.tensor(y)
print(t)

"""
-0.05 -0.05
tensor([ 0.0000, -0.0500, -0.0500,  0.0000])
1.05 -0.05
tensor([ 0.0000,  1.0500, -0.0500,  0.0000])
-0.05 1.05
tensor([ 0.0000, -0.0500,  1.0500,  0.0000])
1.05 1.05
tensor([0.0000, 1.0500, 1.0500, 0.0000])
"""
``````

Thatâ€™s got it! Thank you!