# How to extract the adjacency matrix associated with a subgraph defined by FindPath

For a directed graph g, one can obtain its adjacency matrix as:

SeedRandom[3];
g = RandomGraph[{10, 20}, DirectedEdges -> True, VertexLabels -> "Name"]


Then, a subgraph of g defined by all the pathways from vertex 6 to 4 is:

fp = FindPath[g, 6, 4, Infinity, All]
hfp = HighlightGraph[g, Subgraph[g, fp, VertexLabels -> "Name"]]


I want to find the adjacency matrix of hfp, showing the highlighted edges in hfp in a 10 by 10 matrix (the size of the original digraph g).

• Have you tried PathGraph? Like this: pgs = PathGraph /@ fp; You can then get the matrices for all paths AdjacencyMatrix /@ pgs and combine those. Cycles won't be preserved though. Apr 25, 2021 at 20:23
• Also what's wrong with just sg // AdjacencyMatrix where sg = Subgraph[g, fp, VertexLabels -> "Name"]; ? Apr 25, 2021 at 20:28
• @flinty: Both of your suggestions generate a (5,5) AdjacencyMatrix. However, I want to create a (10,10) Adjacency Matrix (the size of the original directed graph) which incorporates the paths generated. Apr 25, 2021 at 20:38

am = AdjacencyMatrix[Graph[VertexList @ g, EdgeList @ Subgraph[g, fp]]];

am // MatrixForm // TeXForm


$$\left( \begin{array}{cccccccccc} 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 & 0 & 1 & 0 & 0 & 0 & 1 \\ 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 1 \\ 0 & 0 & 0 & 1 & 0 & 0 & 0 & 0 & 0 & 0 \\ 0 & 1 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 & 1 & 0 & 0 & 0 & 0 & 0 \\ \end{array} \right)$$

For a subgraph of g defined by all the pathways from vertex 6 to vertex 4, find the adjacency matrix that represents only the edges of the subgraph of the paths.

SeedRandom[3];
g = RandomGraph[{10, 20}, DirectedEdges -> True, VertexLabels -> "Name"];
fp = FindPath[g, 6, 4, Infinity, All];


We can find the edges of g that are not in Subgraph[g, fp] using Complement[EdgeList[g], EdgeList[Subgraph[g, fp]]], then remove these edges from g using EdgeDelete. The adjacency matrix of g2 is the matrix of g with only the edges of the subgraph.

g2 = EdgeDelete[g, Complement[EdgeList[g], EdgeList[Subgraph[g, fp]]]];

$${\small\left( \begin{array}{cccccccccc} 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 & 0 & 1 & 0 & 0 & 0 & 1 \\ 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 1 \\ 0 & 0 & 0 & 1 & 0 & 0 & 0 & 0 & 0 & 0 \\ 0 & 1 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 & 1 & 0 & 0 & 0 & 0 & 0 \\ \end{array} \right)}$$
Sort@EdgeList[Subgraph[g, fp]] === EdgeList[g2]