Here's an implementation of Dijkstra's Algorithm in MATLAB using an adjacency matrix to represent the graph.
main.m1184 chars27 linesThis function takes as input an adjacency matrix adj and a starting vertex start, and returns two arrays dist and prev representing the shortest path from start to every other vertex in the graph. The dist array contains the distance between start and each vertex, while the prev array contains the previous vertex on the shortest path to each vertex.
The while loop runs until all vertices have been visited, and each iteration selects the unvisited vertex with the smallest dist value. The neighbors of the current vertex are then examined, and their distances and previous vertices are updated if a shorter path is found.
Note that this implementation assumes that the graph is connected, and that all edge weights are non-negative. If the graph is not connected, the algorithm will need to be run separately for each connected component. If the edge weights are negative, a different algorithm such as Bellman-Ford should be used.
gistlibby LogSnag