function[TRewirez]=TRewire(M,p)
%The inputs are a Laplacian matrix M and a scalar p. The output TRewirez
%is a Laplacian Matrix of the graph corresponding to M after rewiring
%each connection with probability p.
[m,n]=size(M);
TRewired=zeros(m);
%TRewired will be the adjacency matrix of TRewirez.
%This block will go through the upper diagonal part of M, which contain all
%the connections of the original graph.
for j=1:m-1
for k = j+1:m
if M(j,k)==0 && TRewired(j,k)==0
%ie: If vertices j and k were not connected originally and not yet
%connected, leave them unconnected.
TRewired(j,k)=0;
else if M(j,k)==0 && TRewired(j,k)<0
%ie: If vertices j and k were not connected originally but were
%already rewired to be connected, preserve the new connection.
TRewired(j,k)=TRewired(j,k);
else
%ie: Vertices j and k were connected.
C=rand(1);
if C>p
%If the random number C is greater than p, do not rewire.
TRewired(j,k)=M(j,k);
elseif isempty(intersect(M(j, :), 0))==1
%If the random number C is less than p but vertex j is already
%connected to all other vertices, preserve the connection.
TRewired(j,k)=M(j,k);
else
%If the random number C is less than p and vertex j is not
%connected to at least one vertex, use the function RandomPick
%to choose an unconnected vertex (z) and rewire the connection
%between j and k to that between j and z.
z=RandomPick(M,j);
if z>j
TRewired(j,z)=-1;
TRewired(j,k)=0;
else
TRewired(z,j)=-1;
TRewired(j,k)=0;
end
end
end
end
end
end
%This code creates the Laplacian Matrix TRewirez out of the adjacency
%matrix TRewired.
X=TRewired+TRewired';
TRewirez=X-diag(sum(X));
end