# Are there any good mass row/column swapping functions for matrices?

I have the following matrix

Keeping the 20 row and 20 column fixed (so the 21st rows and columns because I started at 0)...how do I push each row and column back one spot?

I need to push the 0th row and column to the 19th row and column, the 1st row and column to the 0th row and column..so pretty much swapping out every row and column with the one before it while keeping the 20th row and column fixed.

$\begin{bmatrix}a_{0,0} &a_{0,1}&....&a_{0,20}\\.&.&&.\\.&.&&.\\.&.&&.\\a_{20,0} & a_{20,1}&....&a_{20,20}\end{bmatrix}$

Small example on 5x5 matrix:

pp = Table[p[i, j], {i, 5}, {j, 5}]


One way:

pp[[#, #]] &@Insert[Rest@Range[5], 1, -2]


Or another:

pp[[;; 4, ;; 4]] = RotateLeft[pp[[;; 4, ;; 4]], {1, 1}];

• If you don't want to modify pp, just create new m = pp and do this on m.
– Kuba
Apr 16, 2015 at 11:56
• It's not working up to par with mine. Just making sure, if I have: p[0,1] p[0,2]................p[0,20] . . . . . . . . . p[20,1] p[20,2]..............p[20,20] Would my code be like: pp[[;; 20, ;; 20]] = RotateLeft[pp[[;; 20, ;; 20]], {0, 0}]; pp // MatrixForm? Apr 16, 2015 at 12:01
• @JohnYates What do you mean by not working? Yes, something like that. p.s. MatrixForm is only to show result nicely.
– Kuba
Apr 16, 2015 at 12:14
• @kabu I added an image file with the respective problem Apr 16, 2015 at 12:30
• @JohnYates You rotate by {0,0}, not {1,1}...
– Kuba
Apr 16, 2015 at 12:32

I'm a bit late coming in here with this, but let there be a different approach anyway. It so happens, that the permutation you describe is simply Cycles[{Range@20}]:

Permute[Range@21,Cycles[{Range@20}]]
(* {20, 1, 2, ..., 19, 21} *)


With mat = Table[p[i,j],{i,0,20},{j,0,20}] You can try this:

Transpose@
MapAt[Permute[#, Cycles[{Range@20}]] &,
Transpose@MapAt[Permute[#, Cycles[{Range@20}]] &, mat, {;; 20}],
{;; 20}]


This will return you the complete desired output without having to modify parts of the matrix step-by-step.

Note to self and question to audience: because I have to permute first rows, then columns, I needed to make transpositions. It would be great if there's a way to have MapAt act on an entire column, similar to how here it acted on rows.

• You can MapAt e.g.: {All, 1}. mathematica.stackexchange.com/a/31173/5478
– Kuba
Apr 16, 2015 at 13:42
• In this case this does not work, and probably never will, simply because of the way data is ordered in the list. Instead of operating with Permute on a list of elements constituting the first column of the matrix it operates with Permute on each element in the column separately and, naturally, returns an error. Apr 16, 2015 at 13:47