How can I find the distance between 2 points
5 views (last 30 days)
Show older comments
Hi
I've been working on the shortest path problem and I want to be able to type in a command that finds the distance and the route MATLAB took between 2 points.
And then I want it to highlight the route
This is my code
%Shortest Path Problem%
clearvars
%Distances between each node%
W = [1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1.41 1.41 1.41 1.41 1.41 1.41 1.41 1.41 1.41 1.41 1.41 1.41 1.41 1.41 1.41 1.41 1.41 1.41 1.41 1.41 1.41 1.41 1.41 1.41 1.41 1.41 1.41 1.41 1.41 1.41 1.41 1.41 1.41 1.41 1.41 1.41 0.71 0.71 0.71 0.71 0.71 0.71 0.71 0.71 0.71 0.71 0.71 0.71 0.71 0.71 0.71 0.71];
%Starting Position%
S = [1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9 10 10 11 11 12 12 13 13 14 14 15 15 16 16 17 17 18 18 19 19 20 20 1 2 19 3 18 8 13 19 12 3 8 4 7 18 13 17 14 1 19 2 20 2 18 3 19 7 3 4 8 5 7 4 6 18 14 13 17 14 16 17 15 13 9 8 12 3 13 8 18 9 11 10 12 21 8 21 18 21 13 21 3 22 9 22 12 22 10 22 11];
%Ending Position%
T = [2 1 3 2 4 3 5 4 6 5 7 6 8 7 9 8 10 9 11 10 12 11 13 12 14 13 15 14 16 15 17 16 18 17 19 18 20 19 1 20 19 2 18 3 13 8 12 9 8 3 7 4 13 18 14 17 19 1 20 2 18 2 19 3 3 7 8 4 7 5 6 4 14 16 17 13 16 14 15 17 9 13 12 8 13 3 18 8 11 9 12 10 8 21 18 21 13 21 3 21 9 22 12 22 10 22 11 12];
DG = sparse(S,T,W,22,22);
%Changing the names of the Nodes%
Names = {'Node1','Node2','Node3','Node4','Node5','Node6','Node7','Node8','Node9','Node10','Node11','Node12','Node13','Node14','Node15','Node16','Node17','Node18','Node19','Node20','Point1','Point2'};
%Repositioning Nodes%
%x-coordinates%
x = [1 3 5 5 5 7 7 7 9 11 11 9 7 7 7 5 5 5 3 1 6 10];
%y-coordinates%
y = [2 2 2 6 10 10 6 2 2 2 -2 -2 -2 -6 -10 -10 -6 -2 -2 -2 0 0];
G = digraph(DG,Names);
plot(G,'XData',x,'YData',y);
Any help would be appreciated
0 Comments
Answers (2)
Walter Roberson
on 1 Nov 2017
shortestpath(G, source_node, destination_node)
to get the path. You would still want distances(G, source_node, destination_node) to find the weighted distance.
See Also
Categories
Find more on Graph and Network Algorithms 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!