# How to sort the adjecency matrix of bipartite graph so to have two off-diagonal blocks

In a bipartite graphs there are two class of nodes, say A and B. Each node of class A may interact only with nodes of the class B, and viceversa. The corresponding adjecency matrix is thus composed by two off-diagonal blocks (if you sort the vertices in an appropriate way).

I realize that when working with adjecency matrix for a given bipartite graphs, sometimes I get the desired order in the adjecency matrix, and thus if I plot it, it is formed by two off-diagonal blocks:

g1=CompleteGraph[{5,3}]


However, sometimes if I plot the adjecency matrix directly from the bipartite graphs, now it is not in the desired order:

l2 = CompleteGraph[{5, 3}] // EdgeList;
weights = RandomReal[{0.5, 2}, Length[l2]];
g2 = Graph[l2, EdgeWeight -> weights, GraphLayout -> "BipartiteEmbedding"]


I'm trying to find a way to automatically sort m2 so to tranform it in a two off-diagonal blocks matrix.

-
Note that Dropbox links do not return images, but images embedded in HTML. You need to upload the images to the SE host via the image button above the edit window. – Michael E2 Apr 19 '14 at 19:41

Rows and columns of the adjacency matrix follow the order given by VertexList

And from the docs on VertexList:

Vertices are taken in the order they appear in the list of edges.

Thus, you have

{VertexList[g1], VertexList[g2]}
(* {{1, 2, 3, 4, 5, 6, 7, 8}, {1, 6, 7, 8, 2, 3, 4, 5}} *)


So, you can give an explicit list of vertices as the first argument of Graph to keep the adjacency matrix unchanged:

l2 = CompleteGraph[{5, 3}] // EdgeList;
v2 = CompleteGraph[{5, 3}] // VertexList;
weights = RandomReal[{0.5, 2}, Length[l2]];
g3 = Graph[v2, l2, EdgeWeight -> weights, GraphLayout -> "BipartiteEmbedding"]


Update: Alternatively, you can re-arrange the rows and columns of AdjacencyMatrix[g2] ex post using Ordering as in @Wouters answer:

g2 = Graph[l2, EdgeWeight -> weights,  GraphLayout -> "BipartiteEmbedding"];

maybe Map[Part[#,Ordering[First[Normal[m2]]]]&,Normal[m2],{0,1}]` ?