# General way to permute rows in a matrix (tensor)

I have a matrix:

$m=\begin{bmatrix} a & b & c & d\\ e & f & g & h\\ i & j & k & l\\ m & n & o & p\\ q & r & s & t\\ u & v & w & x \end{bmatrix}$

and I want to sort the rows of the matrix using a sort list:

$sortVec=\left\{ \left\{ 2,1,3\},\{3,1,2\}\right\} \right\}$

so that the output is:

$m=\begin{bmatrix} e & f & g & h\\ a & b & c & d\\ i & j & k & l\\ q & r & s & t\\ u & v & w & x\\ m & n & o & p \end{bmatrix}$

The problem is that when I want to use something like:

Permute[data, sortVec]


then sortVec would need to be

sortVec={2,1,3,6,5,4}


but I don't want to type out the entire vector, but rather permute parts of the matrix...

• Your second matrix doesn't match up with your $sortVec$. If it did, then this would work: m[[Catenate[sortVec + 3 Range[0, Length@sortVec - 1]]]] – Jason B. Aug 9 '16 at 16:30
• Possible duplicate of Sort rows in a matrix with a vector – Jason B. Aug 9 '16 at 16:30
• @JasonB, please look at my edit. – henry Aug 9 '16 at 16:36
• People here generally like users to post code as Mathematica code instead of images or TeX, so they can copy-paste it. It makes it convenient for them and more likely you will get someone to help you. You may find this this meta Q&A helpful – Michael E2 Aug 9 '16 at 17:31

I think this does what you want:

m = Partition[Alphabet[], 4];

sortVec = {{2, 1, 3}, {3, 1, 2}};

Permute[m, Join @@ FoldList[Max[#] + #2 &, sortVec]]


$\left( \begin{array}{cccc} \text{e} & \text{f} & \text{g} & \text{h} \\ \text{a} & \text{b} & \text{c} & \text{d} \\ \text{i} & \text{j} & \text{k} & \text{l} \\ \text{q} & \text{r} & \text{s} & \text{t} \\ \text{u} & \text{v} & \text{w} & \text{x} \\ \text{m} & \text{n} & \text{o} & \text{p} \\ \end{array} \right)$

It also works with mixed cycle lengths:

{{2, 1}, {3, 1, 2}, {1}};

Join @@ FoldList[Max[#] + #2 &, %]

Permute[m, %]

{2, 1, 5, 3, 4, 6}


$\left( \begin{array}{cccc} \text{e} & \text{f} & \text{g} & \text{h} \\ \text{a} & \text{b} & \text{c} & \text{d} \\ \text{m} & \text{n} & \text{o} & \text{p} \\ \text{q} & \text{r} & \text{s} & \text{t} \\ \text{i} & \text{j} & \text{k} & \text{l} \\ \text{u} & \text{v} & \text{w} & \text{x} \\ \end{array} \right)$

• Wizard Great ! Thank you very much! – henry Aug 9 '16 at 16:47
• @DoHe You're welcome. However I see a possible problem; is your sortVec always composed of lists of the same length, or could you have something like sortVec = {{2, 1}, {3, 1, 2}, {1}}? If the latter we will need something more general. – Mr.Wizard Aug 9 '16 at 16:49
• hmm you are right, it would probably need something more general. – henry Aug 9 '16 at 16:53
• @DoHe Please see the update. – Mr.Wizard Aug 9 '16 at 16:54
• Wizard: Great work !! Thank you! – henry Aug 9 '16 at 17:08