Skip to main content

list manipulation - Sort rows in a matrix with a vector



Let's suppose I have a matrix:


$A=\left[\begin{array}{ccc} a & b & c\\ d & e & f\\ g & h & i \end{array}\right]$


and I want to sort the rows using a sort-vector:


$sortVec=\left[\begin{array}{c} 1\\ 3\\ 2 \end{array}\right]$


This would mean that my second row in matrix A would need to be placed at row number 3 and the thrid row would need to be placed at row number 2.


Outcome:


$A=\left[\begin{array}{ccc} a & b & c\\ g & h & i\\ d & e & f \end{array}\right]$



How can I do it in Mathematica?


my question aims at a simple solution. As far as I can see, it is not a duplicate of "Elegant operations on matrix rows and columns".



Answer



You are asking for a permutation, so use Permute


m = Partition[Symbol /@ CharacterRange["a", "i"], 3]


{{a, b, c}, {d, e, f}, {g, h, i}}



Permute[m, {1, 3, 2}]



{{a, b, c}, {g, h, i}, {d, e, f}}



Comments