MATLAB: Is there a way when using shortestpath to not only get the sequence of the nodes but also the edges between those nodes as output

shortestpath

Hello everyone, my Name is Johanna and I am from Germany, so please excuse my English. I am new to Matlab(R2016a) and not really experienced using it. Right now all I can rely on is the MathWorks Help site. I am currently working on a navigation solution with a fairly simple weighted directed graph, consisting of 6 nodes and 12 edges. I used the digraph function to create the graph and weighted the edges by the distances of the connected nodes. I also "attributed" the edges with attributes like Radius and Slope. So using the shortestpath function, I get a path containing the nodes. I tried a few thing like idxOut to get the edges, which build the path, but I do now know how to get the path in a form to automatically work with the idxout function. E.g. the path is [1 2 4 6] and the idxout would be idxout=findedge(G,[1 2 4], [2 4 6]. And what I want is an output not only of the nodes, but the edges you have to drive by and their attributes. I searched the help site but couldn't really find anything. Your help is much appreciated. If there is anything else you need to know about my (I guess pretty easy for you guys) problem, please let me know. Thank you. Johanna

Best Answer

You've pretty much done all the work already. Once you have the indices to the edges, all you need to do is query the graph's edge table for any properties associated with those nodes.
% Create a simple graph
s = [1 1 2 3 3 4 4 6 6 7 8 7 5];
t = [2 3 4 4 5 5 6 1 8 1 3 2 8];
G = graph(s,t);
% Add a new property to the edge table
G.Edges.var = rand(G.numedges,1);
Take a quick look at the edge table:
>> G.Edges
ans =
EndNodes var
________ ________
1 2 0.77016
1 3 0.32247
1 6 0.78474
1 7 0.47136
2 4 0.035763
2 7 0.17587
3 4 0.72176
3 5 0.47349
3 8 0.15272
4 5 0.34112
4 6 0.60739
5 8 0.19175
Now look for the shortest path
% Find shortest path between 2 nodes
pth = shortestpath(G,7,8);
% Edges along that path
eidx = findedge(G, pth(1:end-1), pth(2:end));
And look at values along that path:
>> G.Edges.var(eidx)
ans =
0.47136
0.32247
0.15272