# Generate Permutation Matrix in Numpy

Here we generate the Permutation matrix of any given permutation using Numpy.

The permutation is inputted as a 2-dimensional array in the form of Cauchy 2 line form
like shown below:

#Program to generate the permutation matrix of any given permutation
#Author: Shreyak Chakraborty (C) 2018

import numpy as np

N=8  #number of elements involved in the permutation

E=np.identity(N)  #N X N identity matrix

#the permutation in Cauchy 2 line form
permutation=np.array([[0,1,2,3,4,5,6,7],[0,4,2,6,1,5,3,7]])   #butterfly permutation example

P=np.zeros([N,N]) #initialize the permutation matrix

for i in range(0,N):
P[i]=E[permutation[i]]


We now display the generated matrix as a numpy array of integers

#Display the Permutation Matrix

P.astype(int)


Output:
array([[1, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 0, 0, 0],
[0, 0, 1, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 1, 0],
[0, 1, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 1, 0, 0],
[0, 0, 0, 1, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 1]])


We now test it for the sample input vector. Note the transpose operation since we input a row vector.. The np.matmul() function is used for matrix multiplication

#Test it for another sequence of numbers in range(0,8)

np.matmul(P,np.transpose([3,2,1,4,5,6,0,7])).astype(int)


Output: array([3, 5, 1, 0, 2, 6, 4, 7])