matlab有向网络节点之间最短路经计算
clc;
clear;
% 定义边列表(源节点,目标节点,权重)
w1=[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1];
s1= [1,1,1,1,1,1,2,2,2,2,3,3,3,3,3,3,3,4,5,6,7,7,8,9,10,10,10,11,11,11,12,13,14,14,15,15,15,16,17,18,19,19,21,22,22,22,23,24,24,25];
t1 =[3,24,4,7,5,9,19,20,21,17,1,7,8,12,13,16,18,7,6,5,4,8,7,10,9,24,14,6,12,15,11,14,10,13,11,16,17,15,15,19,18,22,22,19,21,23,22,10,25,24];
% 创建有向图
G = digraph(s1, t1, w1);
% 可视化图
plot(G, 'EdgeLabel', G.Edges.Weight)
% 获取所有节点的索引
nodes = 1:numnodes(G);
% 初始化一个矩阵来存储最短路径(初始化为NaN表示未计算)
shortestPaths = NaN(numnodes(G), numnodes(G));
% 遍历所有节点对
for i = nodes
for j = nodes
% 如果i和j是连通的,则计算它们之间的最短路径
%if isconnected(G, i, j)
% shortestPaths(i, j) = shortestpath(G, i, j);
%end
try
% 注意:如果i和j不连通,shortestpath会抛出错误,但我们用try-catch捕获它
shortestPaths(i, j) = length(shortestpath(G, i, j)); % 使用长度作为距离
catch ME
% 如果i和j不连通,则最短路径为Inf
if strcmp(ME.identifier, 'MATLAB:graph:shortestPath:notConnected')
shortestPaths(i, j) = Inf;
else
% 抛出其他类型的错误
rethrow(ME);
end
end
end
end
% 打印最短路径矩阵
disp(shortestPaths);
#####################
QQ 3087438119