Periodic boundary condition

Suppose I have

tensor([[[-1., 1., 1., 1.],
         [1., 1., 1., 1.],
         [-1., 1., 1., 1.],
         [1., 1., 1., 1.]]])

How can I get

tensor([[[-1., 1., 1., 1., -1],
         [1., 1., 1., 1., 1.],
         [-1., 1., 1., 1., -1],
         [1., 1., 1., 1., 1],
         [-1., 1., 1., 1., -1]]])

In particular, for a N x N matrix, I want another N+1 x N+1 matrix such that the (N+1)th entry is the same as the 0th entry.

Also, I have multiple matrices. For instance, I have 50 4 x 4 matrixes. I want 50 new 5 x 5 matrices after the above operation.

Hi,

I think you will have to use cat for that:

import torch

a = torch.tensor([[[-1., 1., 1., 1.],
          [1., 1., 1., 1.],
          [-1., 1., 1., 1.],
          [1., 1., 1., 1.]]])

out = torch.cat([a, a.narrow(-1, 0, 1)], -1)
bottom = torch.cat([a.narrow(-2, 0, 1), a.narrow(-2, 0, 1).narrow(-1, 0, 1)], -1)
res = torch.cat([out, bottom], -2)

print(res)
>>> tensor([[[-1.,  1.,  1.,  1., -1.],
         [ 1.,  1.,  1.,  1.,  1.],
         [-1.,  1.,  1.,  1., -1.],
         [ 1.,  1.,  1.,  1.,  1.],
         [-1.,  1.,  1.,  1., -1.]]])

Thank you so much :pray:
That was what I needed precisely.