How to find all related nodes in directed graph?
11 次查看(过去 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.
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/326324/image.jpeg)
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!