How to code a factorial matrix combination in Python

Question:

Consider the following input matrix (- are arbitrary values):

  A B C D E F
A - - - - - -
B - - - - - -
C - - - - - -
D - - - - - -
E - - - - - -
F - - - - - -

This input matrix has to be rearranged according to the arbitrary values in it (some optimization calculation) and the only rule is that the column order must match the row order. i.e. one possible result matrix (let’s call it temp_matrix) could be:

  C E A F D B 
C - - - - - -
E - - - - - -
A - - - - - -
F - - - - - -
D - - - - - -
B - - - - - -

Thus, it would seem that the possible number of combinations is 6! i.e. 6x5x4x3x2x1=720 combinations to check.

How to code this in Python to run through all possible matrix arrangement combinations?

In other words: how to create loops which will rearrange the A-F input matrix 720 times, into each possible "rearranged matrix" (i.e. each possible temp_matrix) which can then used for further calculations?

Thank you

Asked By: Roel Van de Paar

||

Answers:

As advised in the comments, use itertools.permutations:

a = np.random.randint(0,10,(3,3)) 
#array([[5, 2, 0],
#       [8, 4, 9],
#      [9, 3, 5]])

from itertools import permutations

for inds in permutations(range(a.shape[0]), a.shape[0]):
    inds = list(inds)
    aperm = a[:,inds][inds]
    print(aperm)
     
#[[5 2 0]
# [8 4 9]
# [9 3 5]]
#[[5 0 2]
# [9 5 3]
# [8 9 4]]
#[[4 8 9]
# [2 5 0]
# [3 9 5]]
#[[4 9 8]
# [3 5 9]
# [2 0 5]]
#[[5 9 3]
# [0 5 2]
# [9 8 4]]
#[[5 3 9]
# [9 4 8]
# [0 2 5]]

Answered By: dermen