function shortest_path = floyd_algorithm(A, source, destination)
% Check if A is a square matrix
if ~isequal(size(A,1), size(A,2))
error('Input matrix A must be square.');
end
% Initialize the distance matrix D with the input adjacency matrix
D = A;
% Get the number of vertices
n = size(D,1);
% Initialize the predecessor matrix P
P = zeros(n);
% Floyd's algorithm
for k = 1:n
for i = 1:n
for j = 1:n
if D(i,k) + D(k,j) < D(i,j)
D(i,j) = D(i,k) + D(k,j);
P(i,j) = k;
end
end
end
end
% Handle the two cases
if nargin == 1
shortest_path = D;
else
if isempty(source) || isempty(destination)
error('Please provide both source and destination.');
end
shortest_path = [D(source, destination), find_path(P, source, destination)];
end
end
function path = find_path(P, source, destination)
if source == destination
path = [source];
else
path = [find_path(P, source, P(source, destination)), destination];
end
end
To use this function, you can call it with the adjacency matrix as the only argument to get the shortest paths between all pairs of vertices, or you can call it with the adjacency matrix and the source and destination vertices as arguments to get the shortest path between the specified vertices. For example:
This function assumes that the input adjacency matrix A has 0s on its diagonal (i.e., there are no self-loops) and positive integers for the edge weights. If your adjacency matrix has different conventions, you may need to modify the function accordingly.