dijkstra's algorithm in matlab

main.m
function [shortestDistances, previousNodes] = dijkstra(graph, startNode)
    numNodes = length(graph);
    
    shortestDistances = inf(1, numNodes);
    shortestDistances(startNode) = 0;
    
    previousNodes = zeros(1, numNodes);
    
    unvisitedNodes = 1:numNodes;
    
    while ~isempty(unvisitedNodes)
        [~, currentNodeIndex] = min(shortestDistances(unvisitedNodes));
        currentNode = unvisitedNodes(currentNodeIndex);
        
        neighbors = find(graph(currentNode, :) > 0);
        for i = 1:length(neighbors)
            neighbor = neighbors(i);
            tentativeDistance = shortestDistances(currentNode) + graph(currentNode, neighbor);
            if tentativeDistance < shortestDistances(neighbor)
                shortestDistances(neighbor) = tentativeDistance;
                previousNodes(neighbor) = currentNode;
            end
        end
        
        unvisitedNodes = setdiff(unvisitedNodes, currentNode);
    end
end
964 chars
28 lines

This function implements Dijkstra's algorithm in MATLAB. You need to provide a graph represented as an adjacency matrix where non-zero values represent edge weights between nodes. The startNode parameter specifies the node from which to calculate the shortest paths to all other nodes. The function returns shortestDistances, an array containing the shortest distances from the startNode to all other nodes, and previousNodes, an array containing the previous node in the shortest path to each node.

related categories

gistlibby LogSnag