MATLAB Examples

Contents

Define the graph edge

s = [1 1 2 2 3 4 4 5 6 6 7 8  9  10];
t = [2 6 3 4 5 5 7 8 7 9 8 11 10 11];
% Define the time between each node
minutes = [28 16 10 16 12 15 4 5 20 7 14 6 8 26];

Define a graph object

G = graph(s, t, minutes);
h = plot(G, 'EdgeLabel', G.Edges.Weight);

% Setting properties of a figure
h.XData = [-1.1 -1.1 -1.1 0   -0.1 0    0.4 0.4 0.8  0.9  1.1];
h.YData = [-2.3 0.7  2    0.7 2    -1.7 0.7 1.8 -1.8 -0.9 1.8];
ylim([-2.7 2.7])
xlim([-1.5 1.5])
h.MarkerSize = 8;

Highlight start and goal

start = 1;
goal = 11;
highlight(h, [start goal], 'NodeColor', 'r')

Calculate the path which takes shortest time

[s_path, d] = shortestpath(G, start, goal);

% Highlight the shortest path
highlight(h, s_path,'EdgeColor','r','LineWidth',2);
h.EdgeLabel = {};

% Display the shortest time
title(['Shortest path takes ', num2str(d), 'min.'])