Create a directed graph with 6 nodes and 11 edges.
W = [.41 .99 .51 .32 .15 .45 .38 .32 .36 .29 .21];
DG = sparse([6 1 2 2 3 4 4 5 5 6 1],[2 6 3 5 4 1 6 3 4 3 5],W)
DG =
(4,1) 0.4500
(6,2) 0.4100
(2,3) 0.5100
(5,3) 0.3200
(6,3) 0.2900
(3,4) 0.1500
(5,4) 0.3600
(1,5) 0.2100
(2,5) 0.3200
(1,6) 0.9900
(4,6) 0.3800
Display the graph.
h = view(biograph(DG,[],'ShowWeights','on'))
Biograph object with 6 nodes and 11 edges.
Find the shortest path from node 1 to node 6.
[dist,path,pred] = graphshortestpath(DG,1,6)
dist = 0.9500
path = 1×4
1 5 4 6
pred = 1×6
0 6 5 5 1 4
Mark the nodes and edges of the shortest path by coloring them red and increasing the line width.
set(h.Nodes(path),'Color',[1 0.4 0.4])
edges = getedgesbynodeid(h,get(h.Nodes(path),'ID'));
set(edges,'LineColor',[1 0 0])
set(edges,'LineWidth',1.5)
pred contains predecessor nodes of the shortest paths from node 1, the source node, to all other nodes, not only the specified destination node. You can use pred to query the shortest paths from the source node to any other node in the graph.
For instance, to figure out the shortest path from node 1 to node 4 using the information in pred, query pred with the destination node as the first query. Then use the returned answer to get the next node. Repeat this procedure until you get the query answer as 0, which indicates the source node.
next = pred(4)
next = 5
next = pred(next)
next = 1
next = pred(next)
next = 0
The results indicate that the shortest path from node 1 to node 4 is 1->5->4.