# How do I stack columns of a 2D tensor sequentially

If I have a 2D tensor (matrix) of size say (5,6), how do I transform it into a (10,3) matrix where each column in the resultant matrix is formed by stacking two consecutive columns in the initial matrix, with a step size of 2. That is, first two columns in the initial matrix are stacked to form the first column in the resultant matrix , 3rd and 4th columns in the initial matrix stacked to obtain the second column in the new matrix and likewise

In a more general sense I want to slide a window, width-wise where all columns in a window are stacked to form single column

This should work for your shapes:

``````x = torch.arange(5*6).view(5, 6)
print(x)

y = x.permute(1, 0).contiguous().view(3, 10).permute(1, 0)
print(y)
``````

I’m unsure what the most efficient way would be so let’s wait if others can come up with a better approach.

1 Like

Thank you for the quick response. For a more general case, suppose If I want to move a sliding window with overlapping columns, is there any approach without writing any loops.

For example in `y` I want first column to be first and second columns of `x` stacked, and second column of `y` to be second and third columns of `x` stacked together.

To create windows you could use `tensor.unfold`, which is also known as the `im2col` method.

1 Like