Mathematica Stack Exchange is a question and answer site for users of Mathematica. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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.
share|improve this question
Related… – Leonid Shifrin Feb 25 '12 at 17:16
up vote 17 down vote accepted

How about:

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

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

share|improve this answer
Amazingly simple. Shame on me. – István Zachar Feb 25 '12 at 16:57
Glad I could help. – user21 Feb 25 '12 at 16:58
@Istvan the solution is simple, but IMHO not trivial. It's a good question. – Mr.Wizard Feb 25 '12 at 23:16

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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