How to flatten a tensor in column-major order?

I just found that the solution had already been posted on this forum, here:

The answer was:

t = torch.rand(3, 3, 3)

# convert to column-major order
t.set_(t.storage(), t.storage_offset(), t.size(), tuple(reversed(t.stride())))  
t.flatten()  # 1D array in column-major order

Note that if you just want a tensor’s 1D representation in column-major order, the above operation will change the ordering of the elements in tensor t. This function will pull out just the flattened array in column-major order:

def flatten_fortran_w_clone(t):    
    nt = t.clone()
    nt = nt.set_(nt.storage(), nt.storage_offset(), nt.size(), tuple(reversed(nt.stride())))    
    return nt.flatten()

But there might be a better way of doing it without having to create a copy…

1 Like