How to find all related nodes in directed graph?
조회 수: 16 (최근 30일)
이전 댓글 표시
Hi! I have a dirested graph "G" (figure is represented bellow). How can I find all nodes that are ONE BY ONE connected with certain node "n". For example if we talk about node 11 required nodes are 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23.
I tried to use a "successors" function but I'm stcuk. Can anybody help me please? Here's the code (my attempts):
clc; clear;
S = [1 2 3 3 4 5 6 6 8 9 11 11 12 12 14 16 16 17 17 19 20 22];
T = [2 3 4 11 5 6 7 8 9 10 12 16 13 14 15 17 22 18 19 20 21 23];
weight = [0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0];
G = digraph (S, T, weight);
B = [S' T' weight'];
for i = 1:22
if B(i,3)==1
N = successors (G, B(i,2)) %% equivalent of N = (12; 16)
k = N';
for j=1:length(N)
N = successors(G,N(j))
end
end
end
댓글 수: 0
답변 (2개)
Steven Lord
2020년 7월 3일
You want to know all nodes that are reachable from the designated node? Use the distances function on the digraph with the designated node as the source node.
댓글 수: 0
Christine Tobler
2020년 7월 6일
편집: Christine Tobler
2020년 7월 6일
Another option is to use the weak connected components of the graph:
bins = conncomp(G, 'Type', 'weak');
% bins(nid) gives the id of the connected component that contains node nid.
allNodesInSameComponentAsNode11 = find(bins == bins(11))
댓글 수: 2
Christine Tobler
2020년 7월 10일
Sorry I just came back to this now. On second look, I realize I misinterpreted your question (I thought you were looking for all nodes connected to node 11 when ignoring edge direction).
If you are looking for reachable nodes only, you can use
nearest(G, 11, Inf, 'Method', 'unweighted')
which will return all nodes within distance Inf of node 11, meaning all nodes that are reachable from node 11.
It's also possible to use distances, as Steve suggested, just find all nodes where the distance to node 11 is not Inf.
참고 항목
카테고리
Help Center 및 File Exchange에서 Graph and Network Algorithms에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!