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);
复制代码

 

 

#####################

posted @   西北逍遥  阅读(11)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
历史上的今天:
2023-06-18 QGeoPolygon
2022-06-18 计算关节夹角
2021-06-18 unity3d给某个对象添加材质
2020-06-18 IfcAnnotationFillArea
2020-06-18 IfcGeometricRepresentationItem
2019-06-18 Qt 自定义信号SIGNAL
2019-06-18 qt ui
点击右上角即可分享
微信分享提示