필터 지우기
필터 지우기

How can I get the root node of a given node from a directed graph ?

조회 수: 13 (최근 30일)
Anatole Jimenez
Anatole Jimenez 2019년 12월 18일
댓글: Guillaume 2019년 12월 19일
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

채택된 답변

Guillaume
Guillaume 2019년 12월 18일
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))
  댓글 수: 8
Anatole Jimenez
Anatole Jimenez 2019년 12월 19일
I just tried what you submit but It didn't work.
The bins from the G.conncomp('Type', 'weak') property are not sort with the terminalidx from find(G.outdegree == 0).
By example the node 6 has the node 1019 as terminal but the bins(6) is 2 and terminalidx(2) = 11.
I think bins number are not terminalidx index.
Guillaume
Guillaume 2019년 12월 19일
Indeed, I made an assumption that the terminals would be in the same order as the bins, which is generally incorrect. Fixed code:
bins = G.conncomp('Type', 'weak'); %since the graph is DAG all connections are weak
terminalidx = find(G.outdegree == 0); %which nodes are terminal
terminalbin = bins(terminalidx)
assert(isequal(unique(terminalbin), 1:numel(terminalbin)), 'At least one subgraph has more than one terminal') %optional check
[~, termorder] = sort(terminalbin); %find ordering of terminals according to the bin they're in
terminalidx = terminalidx(termorder); %and reorder them accordingly
matchingterminal = terminalidx(bins); %replicate terminal index in each bin
Note that I would store all this information, together with the nodes X and Y location into the node table:
G.Nodes.Isterminal = G.outdegree == 0;
G.Nodes.MatchingTerminal = matchingterminal;
G.Nodes.Subgraph = bins;
G.Nodes.X = ??? %Nx1 column vector
G.Nodes.Y = ??? %Nx1 column vector
which makes for easy plotting
plot(G, 'XData', G.Nodes.X, 'YData', G.Nodes.Y, 'NodeCdata', G.Nodes.IsTerminal+1); %to highlight the terminals

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Graph and Network Algorithms에 대해 자세히 알아보기

제품

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by