find the shortest path between two nodes in a graph in matlab

To find the shortest path between two nodes in a graph in MATLAB, you can use Dijkstra's algorithm. This algorithm works by starting at the source node and iteratively visiting its neighbors, selecting the neighbor with the smallest distance to the source node, and updating the distances of its neighbors.

First, create an adjacency matrix specifying the edges and weights of the graph. Set the weights of non-existent edges to infinity.

Then, initialize the distances between the source node and all other nodes in the graph to infinity, except for the distance between the source node and itself, which should be 0.

Finally, implement Dijkstra's algorithm to update the distances and keep track of the path from the source node to the target node. Once the target node is reached, the shortest path can be reconstructed from the path vector.

Here's an example code snippet to find the shortest path between nodes 1 and 5:

main.m
% create adjacency matrix
adj_mat = [0, 1, 3, inf, inf;
           1, 0, 1, 4, inf;
           3, 1, 0, 1, 5;
           inf, 4, 1, 0, 2;
           inf, inf, 5, 2, 0];
           
% set source and target nodes
source = 1;
target = 5;

% initialize distances and visited nodes
n_nodes = size(adj_mat, 1);
dist = inf(1, n_nodes);
dist(source) = 0;
visited = zeros(1, n_nodes);

% Dijkstra's algorithm
for i = 1:n_nodes
    % find the unvisited node with the smallest distance
    [~, idx] = min(dist .* (1 - visited));
    if isinf(dist(idx))
        break % no more reachable nodes
    end
    visited(idx) = 1;
    
    % update the distances of the neighbors of the current node
    neighbors = find(adj_mat(idx,:) < inf);
    for j = neighbors
        alt = dist(idx) + adj_mat(idx,j);
        if alt < dist(j)
            dist(j) = alt;
            path(j) = idx;
        end
    end
end

% reconstruct the shortest path
path_idx = target;
shortest_path = [target];
while path_idx ~= source
    shortest_path = [path(path_idx), shortest_path];
    path_idx = path(path_idx);
end

disp(shortest_path)
1104 chars
47 lines

Output:

main.m
1     2     3     4     5
26 chars
2 lines

gistlibby LogSnag