MATLAB: How to get the root node of a given node from a directed graph

digraphdirected graphgraphMATLABnode

Hello,
I am using graph for image processing, 1 node = 1 pixel.
I computed the graph but I need to find for each node its root node.
Is there any function or a quite performant solution as the number of nodes is quite high ?
Thank you,
Anatole Jimenez

Best Answer

the first element of the vector returned by toposort would be your root node. Of course, your graph must be acyclic and if your graph has several roots, this will only be one of them.
Perhaps easier would be to look in the edge table and find which nodes don't appear at all as target nodes. Assuming the Nodes table is empty:
rootnodes = setdiff(1:height(yourgraph.Nodes), yourgraph.Edges.EndNodes(:, 2))
Related Question