how to do forward neighbor discovery in un-directed graph?
2 views (last 30 days)
Show older comments
I have an undirected graph G with 11 nodes and 15 edges. There is a source and destination node and i find neighbors of source node using
n1=neighbors(G,'Source');
next i want to find neighbors of n1 excluding 'Source'. Want to repeat it for neighbors of n1 as well. I only want to select the forward nodes and not the previous ones.
0 Comments
Answers (1)
Christine Tobler
on 14 Feb 2020
If I understand correctly, you want to find all nodes that are direct neighbors of n1, then all nodes that connect to n1 through one other node, but aren't n1 or a direct neighbor of n1. In other words, you need all nodes at distance 1 from n1, at distance 2 from n1, and so on.
Simplest is to compute the distances of every node from n1, and to use that vector:
d = distances(G, 'Source', 'all', 'Method', 'unweighted');
directNeighbors = G.Nodes.Name(d == 1); % this is equivalent to neighbors(G, 'Source')
neighborsDistance2 = G.Nodes.Name(d == 2);
neighborsDistance3 = G.Nodes.Name(d == 3);
Note: If G does not have any edge weights (G.Edges has no variable named 'Weight'), you can also use
d = distances(G, 'Source', 'all');
as the 'Method', 'unweighted' option will have no effect in that case.
2 Comments
Christine Tobler
on 17 Feb 2020
You can use setdiff(successors(G, n1), {'Source'}), which will remove the original source node from the list of successors of n1.
See Also
Categories
Find more on Directed Graphs in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!