% permutations.m
clear

% Generate a random permutation matrix
N=5;
v=rand(5,1);
[u,k]=sort(v);
P=zeros(N,N);
for n=1:N
	P(n,k(n))=1;
end

% Test what P does to a matrix
A=zeros(N,N);
B=zeros(N,N);
for n=1:N
	A(n,:)=(n-1)*N+1:n*N;
	B(:,n)=((n-1)*N+1:n*N)';
end

sprintf('Left-multiplication by a permutation matrix equals a row-exchange')
P, A, P*A
pause

sprintf('Right-multiplication by a permutation matrix equals a column-exchange')
B, P, B*P
pause

% Find the periodicity of P
PP=P;
n=1;
while max(max(PP-eye(N))) > 0
	n=n+1;
	PP=P*PP;
end
sprintf('Power of P that equals the identity')
P, n, P^n
% Can you find the pattern in P that determines the periodicity?