14

Given a symmetric square matrix, how can I apply a permutation to the rows and columns (i.e. the same permutation to both the rows and the columns) such a way that the new structure of the matrix should follow the new row and column order?

Consider an order of rows/columns, according to which the elements of a set are arranged in a matrix:

order = Range[5];
matrix = Table[Subscript[a, i, j], {i, 5}, {j, 5}];
TableForm[matrix, TableHeadings -> {order, order}]

Mathematica graphics

Now take a permutation of the row/column order:

newOrder = RandomSample[order]
(*
   ==> {1, 4, 5, 2, 3}
*)

FindPermutation finds the appropriate permutation cycle for the new order:

permutation = FindPermutation[order, newOrder]
Permute[order, permutation]
(*
   ==> Cycles[{{2, 4}, {3, 5}}]
   ==> {1, 4, 5, 2, 3}
*)

Now the question is: How to easily and elegantly apply the above permutation (preferably in its Cycles form) to the matrix to yield the following one:

Mathematica graphics

Some notes:

  • The matrix is always square and symmetric.
  • Column and head orders are always identical.
  • Bear in mind that order, and consequently matrix, can be big (e.g. 4^8 for order)
  • Since matrix can be big, I'm looking for a method, that applies the permutation 'locally', that is without reconstructing the whole table every time, or without applying replacements/functions enumerating each element, thus no dispatch table should be used. This is rather important, as it could be that the new order only swaps two columns/rows, and nothing else.
István Zachar
  • 47,032
  • 20
  • 143
  • 291
  • 1
    Related question:http://stackoverflow.com/questions/6258349/how-to-form-submatrices-with-some-non-consecutive-rows-and-columns-of-a-matrix/ – Leonid Shifrin Feb 25 '12 at 17:16

1 Answers1

21

How about:

ord = {1, 4, 5, 2, 3}
matrix[[ord, ord]]

(You can convert any permutation (including Cycles) to an index list using PermutationList.)

Szabolcs
  • 234,956
  • 30
  • 623
  • 1,263