Dijkstra's Algorithm Function Problem
2 views (last 30 days)
Show older comments
Here's the code I have so far:
function[sp,spcost]=dijkstra(g,graph(53))
n=size(graph,1);
S(1:n)=0;
dist(1:n)=inf;
prev(1:n)=n+1
dist(graph(53,:)=0
while sum(S)~=n
candidate=[];
for i=1:n
if S(i)==0
candidate=[candidate dist(i)];
else
candidate=[candidate inf];
end
end
[u_index u]=min(candidate);
S(u)=1;
for i=1:n
if (dist(u)+g(u,i))<dist(i)
dist(i)=dist(u)+g(u,i);
prev(i)=u;
end
end
end
sp=[g(53,:)];
while sp(1)~=s
if prev(sp(1))<=n
sp=[prev(sp(1)) sp];
else
error;
end
end
spcost=dist(d);
It is based on Jorge Barrera's code (<http://www.mathworks.com/matlabcentral/fileexchange/14661-dijkstra-very-simple)>. I'm having trouble getting the function to run past the first line because of an "unbalanced bracket". My input is a 194x194 matrix and the goal is to find the shortest path to a certain location (row 53) from every one of the 194 locations. This should return a distance vector.
1 Comment
Muthu Annamalai
on 30 Jul 2013
MATLAB does not require types or dimensions in function declaration
function[sp,spcost]=dijkstra(g,graph(53))
should be
function[sp,spcost]=dijkstra(g,graph)
Accepted Answer
Jan
on 30 Jul 2013
The error message is clear:
function[sp,spcost] = dijkstra(g,graph(53))
You cannot defined an indexed expression in the input arguments of a function. Perhaps you mean:
function[sp,spcost] = dijkstra(g, graph)
0 Comments
More Answers (0)
See Also
Categories
Find more on Dijkstra algorithm 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!