I'm looking for a code that speed up a creation of permutation matrix. i.e., I want to create a matrix of n columns, where each column value iterates over m values, creating a n^m combinations on each row. On the example below, there are 2 methods to create the matrix, in this case n=7 and m=5 that creates a matrix similar to:
1 1 1 1 1 1 1
1 1 1 1 1 1 2
1 1 1 1 1 1 3
1 1 1 1 1 1 4
1 1 1 1 1 1 5
1 1 1 1 1 2 1
...
5 5 5 5 5 5 5
The order of the rows doesn't matter, only that all combinations are created. I have written the following 2 methods to create the arrays, but the metod1 is very slow (although very verbose and clear to understand) and method2 is faster using numpy functions. But I still need to find a faster methodology to create the matrix.
import numpy as np
############################################
def permArray_meth1():
allArray = np.zeros((1,7))
for a1 in range(1,6):
for a2 in range(1,6):
for a3 in range(1,6):
for a4 in range(1,6):
for a5 in range(1,6):
for a6 in range(1,6):
for a7 in range(1,6):
allArray = np.append(allArray, np.array([a1,a2,a3,a4,a5,a6,a7]).reshape(1,7), axis=0)
allArray = np.delete(allArray, 0, 0)
return allArray
############################################
def permArray_meth2():
##### Create permutation matrix #####
a = np.arange(np.power(5,7)).reshape(5,5,5,5,5,5,5)
allArray = [(a1,a2,a3,a4,a5,a6,a7) for a1,a2,a3,a4,a5,a6,a7 in np.ndindex(a.shape)]
##### Convert list to array #####
allArray = np.asarray(allArray)+1
return allArray
############################################
if __name__ == "__main__":
allArray = permArray_meth1() # (50sec)
print 'allArray1', np.shape(allArray)
allArray = permArray_meth2() # (1sec)
print 'allArray2', np.shape(allArray)
I know that the speed is dependent also on the used CPU hardware, but I'm looking for a relatively faster code thatn the shown above.
Is there any other method/code?