Concatenate and sort tensor


I have 2 tensors like below:

hc1 = torch.randn(5,1, 1, 1)
hc2 = torch.randn(5,1, 1, 1)

I want to concatenate these 2 tensors as hc3 and then sort hc3 based on amounts of hc1.
How could I do it?


Could you post a simple example with some values?
You could concatenate these tensor using out =, hc2), dim=dim), however I’m not sure, how you would like to sort the tensors.

Dear ptrblck,

Thanks for your reply. Sure. I simplify my question with changing the dimensions of tensors to 2. Suppose we have these 2 tensors:

hc1 = tensor([[30],


1, 2, 3, 4, 5 are, subsequently, related to 30, 20, 10, 50, 40.
After sorting hc1 we would have 10, 20, 30, 40, 50 and 3, 2, 1, 5, 4. Because hc1 and hc2 are 1 to 1.
I thought that I should concatenate them as hc3 and sort it based on hc1.
I hope that I explained my question as well as possible.


You can get the permutation by calling perm = hc1.argsort(dim=0).squeeze().
In your example it returns tensor([2, 1, 0, 4, 3])

Then you can rearrange hc2 with this permutation : hc2_rearranged = hc2[perm].
In your example it returns


You can always concatenate those afterwards

Thanks for your reply.
I can not understand how to have sorted hc1 while you achieved sorted indices of hc1? Is there any way?


Dear Phan_Phan,

Oh, how funny question I asked. It just needs to write:


Many thanks