implement dijkstras algorithm in matlab

Here's an implementation of Dijkstra's Algorithm in MATLAB using an adjacency matrix to represent the graph.

main.m
function [dist,prev] = dijkstra(adj,start)
%DIJKSTRA Calculates the shortest path in a graph using Dijkstra's algorithm
%   [dist,prev] = dijkstra(adj,start) returns an array of distances (dist)
%   and a corresponding array of previous vertices (prev) representing the
%   shortest path from the start vertex to every other vertex in the graph
%   represented by the adjacency matrix (adj).

n = size(adj,1); % Number of vertices
dist = inf(1,n); % Initialize distances to infinity
prev = zeros(1,n); % Initialize previous vertices to zero

dist(start) = 0; % Distance from start vertex to itself is zero
s = zeros(1,n); % Initialize set of visited vertices to empty

while sum(s) ~= n % While set of visited vertices is not equal to all vertices
    [~,u] = min(dist + inf*s); % Find unvisited vertex with minimum distance
    s(u) = 1; % Add vertex to set of visited vertices
    neighbors = find(adj(u,:) ~= 0); % Find neighbors of current vertex
    for v = neighbors
        alt = dist(u) + adj(u,v); % Calculate alternative distance
        if alt < dist(v)
            dist(v) = alt; % Update distance
            prev(v) = u; % Update previous vertex
        end
    end
end
1184 chars
27 lines

This 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