Matlab图论工具箱
文章目录
稀疏矩阵与普通矩阵的转化
使用工具箱中的命令时,需要将普通矩阵转化为稀疏矩阵
sparse
普通矩阵使用sparse命令变成稀疏矩阵
sparse(S) %将矩阵S转化为稀疏矩阵
sparse(m,n) %生成一个m*n的所有元组都为0的稀疏矩阵
sparse(i,j,v) %i,j,v为3个等长向量,其中i,j为元素v的行标和列表
sparse(i,j,v,m,n) %m,n为满矩阵时的行列值
%i,j,v可由find获得 [i,j,v]=find(A) %A为普通矩阵
tril(a) %截取下三角矩阵
full
稀疏矩阵使用full命令变成普通矩阵
注:有向图和无向图转换为稀疏矩阵方法似乎不同
有向图最大流
graphmaxflow
[max_flow,gra]=graphmaxflow(graph,s,t)
参数
graph 为稀疏矩阵
s 起始节点
t 目的节点
返回值
max_flow 最大流
gra 满足最大流的稀疏矩阵
注意事项
只能解决权重都为正值,且两个顶点之间没有两条弧的问题。若不满足则进行适当处理。
假如两节点之间 v i , v j v_i,v_j vi,vj有两条弧,权重(容量)为 w i j , w j i w_{ij},w_{ji} wij,wji,则可以在 v i , v j v_i,v_j vi,vj之间添加一个虚拟的节点 v k v_k vk,并添加两条弧 w i k , w k j ( 或 w j k , w k , i ) w_{ik},w_{kj}(或w_{jk},w_{k,i}) wik,wkj(或wjk,wk,i),删除= w i j ( 或 w j i ) w_{ij}(或w_{ji}) wij(或wji),其中 w i k = w k j = w i j ( 或 w j k = w k i = w j i ) w_{ik}=w_{kj}=w_{ij}(或w_{jk}=w_{ki}=w_{ji}) wik=wkj=wij(或wjk=wki=wji)
图最小生成树
graphminspantree
[tree,pred]=graphminspantree(graph[,v])
参数
graph为图的稀疏矩阵
v为根节点
返回值
tree为最小生成树
pred为每个节点的的父节点(默认第一个节点为根节点)
其他参数
[Tree, pred] = graphminspantree(..., 'Method', MethodValue, ...)
[Tree, pred] = graphminspantree(..., 'Weights', WeightsValue, ...)
method 默认为prim,可选’Kruskal’
两节点最短路
graphshortestpath
[dist,path,pred]=graphshortestpath(graph,S,T)
graph为稀疏矩阵(可能要求是下三角)
S为起始节点
T为目的节点
dist为最短距离
path为路径
pred为S到每个节点的最短路径中,目标节点的先驱
其他参数
[...] = graphshortestpath(..., 'Directed', DirectedValue, ...)
[...] = graphshortestpath(..., 'Method', MethodValue, ...)
[...] = graphshortestpath(..., 'Weights', WeightsValue, ...)
其中,’Directed’是标志图为有向图或无向图的属性,若图为无向图,属性值为false,有向图为true
‘Method’是使用的算法,默认为’Dijkstra’,还可设’Bellman-Ford’
每对节点间的最短路径
graphallshortestpaths
dist=graphallshortestpaths(DG)
DG为稀疏矩阵
dist为第i个结点到第j个节点的最短距离组成的矩阵(i*J)
其他参数
[dist] = graphallshortestpaths(G, ...'Directed', DirectedValue, ...)
[dist] = graphallshortestpaths(G, ...'Weights', WeightsValue, ...)
其中,’Directed’是标志图为有向图或无向图的属性,若图为无向图,属性值为false
其他工具
命令 | 功能 |
---|---|
graphconncomp | 找无向图的连通分支,或有向图的强(弱)连通分支 |
graphisdag | 测试有向图是否含有圈,不含圈返回1,含圈返回0 |
graphisomorphism | 确定两个图是否同构,同构返回1,否则返回0 |
graphisspantree | 确定一个图是否是生成树,是返回1,否则返回0 |
graphpred2path | 把前驱节点序列变成路径的顶点序列 |
graphtopoorder | 执行有向图无圈图的拓扑排序 |
graphtraverse | 求从一顶点出发,所能遍历的所有图中顶点 |
视图
[h=]view(biograph(tree,nodestr,'ShowArrows','off',ShowWeights,'on'))
其中,nodestr为节点对应的名字,可以[]默认
其他操作
h.EdgeType='segmented'; %边的连接为线段
h.LayoutType='equilibrium'; %设置图形布局属性
dolayout(h); %刷新图形布局