Writing a program to swap rows and columns
Swapping rows
Code.
swapRows[matrix_?SquareMatrixQ] /; EvenQ[Length[matrix]] :=
Module[{mat = matrix, r = Range[2, Length[matrix] - 1]},
mat[[r]] = mat[[Flatten[Reverse /@ Partition[r, 2]]]];
mat
];
Usage.
mat = Partition[Range[36], 6];
mat // MatrixForm
swapRows[mat] // MatrixForm
Swapping columns
Code.
swapColumns[matrix_?SquareMatrixQ] /; EvenQ[Length[matrix]] :=
Module[{mat = matrix, r = Range[2, Length[matrix] - 1]},
mat[[All, r]] = mat[[All, Flatten[Reverse /@ Partition[r, 2]]]];
mat
];
Usage.
swapColumns[mat]
Comments
For other swappings, you will need to generate the list of rows or columns you want to swap in the appropriate way, as mentioned by C.E. in his comment.
The Do
loop comes to mind:
swapR[mat_] := Block[{mat1},
mat1 = ConstantArray[0, Length@mat];
Do[
mat1[[1]] = mat[[1]];
mat1[[Length@mat]] = mat[[Length@mat]];
mat1[[{i, i + 1}]] = mat[[{i + 1, i}]];,
{i, 2, Length@mat - 2, 2}
];
mat1
]
swapC[mat_] := Block[{mat1, matT = Transpose@mat},
mat1 = ConstantArray[0, Length@mat];
Do[
mat1[[1]] = matT[[1]];
mat1[[Length@matT]] = matT[[Length@matT]];
mat1[[{i, i + 1}]] = matT[[{i + 1, i}]];,
{i, 2, Length@matT - 2, 2}
];
Transpose@mat1
]
The idea of swapR
is to define a new matrix, mat1
, with its first and last rows the same as the input matrix mat
. The other rows are interchanged pairwise with the line mat1[[{i, i + 1}]] = mat[[{i + 1, i}]]
- this swaps row i
and i+1
. An (un-tested in the code) assumptions is that there is an even number of rows, so it has to go through i = 2, 4, ...
, hence the iterator of the Do
loop.
Swapping columns is equivalent to swapping rows of a transposed matrix and transposing the result, hence the Transpose
in inserted in the swapC
code.
The RepeatedTiming
s are practically the same as with Xavier's approach.
EDIT: The above codes answer explicitly the OP. A more flexible approach will be as follows.
To swap any two rows i
and j
of a general $m\times n$ matrix:
swapRij[mat_, {i_, j_}] := Block[{mat1 = mat},
mat1[[{i, j}]] = mat[[{j, i}]];
mat1
]
Usage: swapRij[mat, {1, 2}]
swaps the first and second rows of mat
. Note the second argument is a list.
Similarly, to swap any two columns i
and j
:
swapCij[mat_, {i_, j_}] := Block[{matT = Transpose@mat},
matT[[{i, j}]] = matT[[{j, i}]];
Transpose@matT
]
The functions swapRij
and swapCij
can be used on a set of pairs of rows/columns to be swapped. Let's take e.g. mat = Partition[Range[36], 6]
and do
Fold[swapRij[#1, #2] &, mat, {{1, 2}, {3, 4}, {5, 6}}]
swaps the 1st and 2nd, 3rd and 4th, and 5th and 6th rows:
Similarly for Fold
ing swapCij
.