You are on page 1of 2

% THE MATLAB CODE---- TURAB RAFIQ L1S17MSEE0008

% Graph for shortest path - DIJKSTRA ALOGRITHM


s=[1 1 2 2 3 3 3 4 5]; % definition of source for all paths of the graph
t=[2 4 3 4 4 5 6 5 6]; % definition of destination for all paths in graph
weights=[18 15 9 6 14 10 28 7 36]; % definition of the weights for all paths
G = graph(s,t,weights); % command will create the graph of the given values
from source to destination with weights
x = [0.5 0.5 1 0 0.5 0 0.5 1 0.5]; % x component of all the paths
y = [0.5 0.5 0 1 0.5 1 0.5 0 0.5]; % y component for all the paths
plot(G,'EdgeLabel',G.Edges.Weight); % plot command
[path,d] = shortestpath(G,1,6); % finding the shortest path between s and t
will be from 1-6
% it will follow from 1-2-3-6 with a total weight of 55 shown by d . check
the results

% Function of Dijkstra Complete Algorithm

function [e L] = dijkstra(A,s,d)
if s==d % if source and destination is at same point
e=0;
L=[s];
else
A = setupgraph(A,inf,1); % using setup graph command
if d==1
d=s;
end
A=exchangenode(A,1,s);
lengthA=size(A,1);
W=zeros(lengthA);
for i=2 : lengthA
W(1,i)=i;
W(2,i)=A(1,i);
end
for i=1 : lengthA
D(i,1)=A(1,i);
D(i,2)=i;
end
D2=D(2:length(D),:);
L=2;
while L<=(size(W,1)-1)
L=L+1;
D2=sortrows(D2,1);
k=D2(1,2);
W(L,1)=k;
D2(1,:)=[];
for i=1 : size(D2,1)
if D(D2(i,2),1)>(D(k,1)+A(k,D2(i,2)))
D(D2(i,2),1) = D(k,1)+A(k,D2(i,2));
D2(i,1) = D(D2(i,2),1);
end
end

for i=2 : length(A)


W(L,i)=D(i,1);
end
end
if d==s
L=[1];
else
L=[d];
end
e=W(size(W,1),d);
L = listdijkstra(L,W,s,d);
end
G = [0 3 9 0 0 0 0;
0 0 0 7 1 0 0;
0 2 0 7 0 0 0;
0 0 0 0 0 2 8;
0 0 4 5 0 9 0;
0 0 0 0 0 0 4;
0 0 0 0 0 0 0;
];
[cost rute] = dijkstra(G,1,7)

You might also like