Search code examples
wolfram-mathematicaalgebra

Sort a matrix according to one row in Mathematica


I'm fairly new to Mathematica and I've come across a probably stupid problem.

I have a matrix {{1,1,1,2,2,2,2,2},{-1,0,1,-2,-1,0,1,2}} and I would like to sort the second row but also that the positions of the elements of the first row are sorted at the same time.

Thus, the array would become {{2,1,2,1,2,1,2,2},{-2,-1,-1,0,0,1,1,2}}. I hope is it clear. Do you know how I could proceed?

Thanks in advance.


Solution

  • Let

    list = {{1, 1, 1, 2, 2, 2, 2, 2}, {-1, 0, 1, -2, -1, 0, 1, 2}}
    

    then

    {list[[1]][[Ordering[list[[2]]]]], Sort[list[[2]]]}
    

    gives the output you are looking for.

    For future reference, you might want to think about posting Mathematica questions at https://mathematica.stackexchange.com.