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.


$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".

  • 1
    $\begingroup$ a = Partition[Alphabet[][[;; 9]], 3]; a[[{1, 3, 2}]] $\endgroup$ – Jason B. Aug 9 '16 at 14:21
  • 3
    $\begingroup$ just A[[sortVec]] $\endgroup$ – BoLe Aug 9 '16 at 14:25
  • $\begingroup$ @march This is not a duplicate of the one you reference, as sorting is not listed among those operations. However... $\endgroup$ – István Zachar Aug 10 '16 at 11:42
  • $\begingroup$ @IstvánZachar. I somewhat agree with your assessment, although I would say that the OP used the wrong word in "sort", because really this is just rearranging the rows of the matrix, which is a generalization of "swapping two rows". However, either one is fine. $\endgroup$ – march Aug 10 '16 at 15:33

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}}


Not the answer you're looking for? Browse other questions tagged or ask your own question.