#################本文为学习《图论算法及其MATLAB实现》的学习笔记#################
- 有向图:具有有向边的图,包含始点和终点。
- 邻接矩阵(无向图):
表示顶点
与顶点
之间的边数,可能取值为 0, 1 ,2
- 邻接矩阵(有向图):
表示从始点
到终点
之间有向边的条数。
- 关联矩阵(无向图):
表示顶点
与边
关联的次数,可能取值为 0, 1 ,2
= 1, 是有向边
的始点
- 关联矩阵(无向图):
= -1,
是有向边
的终点
=0, 是有向边
的不关联点
- 无向图的关联矩阵和邻接矩阵的相互转化
function W = incandadf(F,f)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%% 无向图的关联矩阵和邻接矩阵的相互转化 %%%%%%%%%%%%%%%%%%%
%%%%%%%%% f = 0 时:input:F 为邻接矩阵; output:W 为关联矩阵 %%%%%%%%%%
%%%%%%%%% f = 1 时:input:F 为关联矩阵; output:W 为邻接矩阵 %%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if f == 0 %邻接矩阵转化为关联矩阵
m = sum(sum(F))/2; %计算 F 中所有元素和/2,即求 F 的边数
n = size(F,1); %计算 F 的行数
W = zeros(n,m); % W 行数与 F 相同,列数为 F 的边数
k = 1;
for i = 1:n
for j = i:n
if F(i,j) ~= 0
W(i,k) = 1; %给边的始点赋值为1
W(j,k) = 1; %给边的终点赋值为1
k = k+1;
end
end
end
elseif f == 1 %关联矩阵转换为邻接矩阵
m = size(F,2); %计算 F 的列数
n = size(F,1); %计算 F 的行数
W = zeros(n,n); % W 维度为 F 的顶点数的方阵
for i = 1:m
a = find(F(:,i) ~= 0); %找到 F 中每列不为零的元素的索引值
W(a(1),a(2)) = 1; %存在边,则邻接矩阵的对应值为1
W(a(2),a(1)) = 1;
end
else
fprint('please input the right value of f');
end
W;
有向图的关联矩阵和邻接矩阵的相互转化
function W = mattransf( F,f )
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%% 有向图的关联矩阵和邻接矩阵的相互转化 %%%%%%%%%%%%%%%%%%%
%%%%%%%%% f = 0 时:input:F 为邻接矩阵; output:W 为关联矩阵 %%%%%%%%%%
%%%%%%%%% f = 1 时:input:F 为关联矩阵; output:W 为邻接矩阵 %%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if f == 0 %邻接矩阵转化为关联矩阵
m = sum(sum(F)); %计算 F 中所有元素和,即求 F 的边数
n = size(F,1); %计算 F 的行数
W = zeros(n,m); % W 行数与 F 相同,列数为 F 的边数
k = 1;
for i = 1:n
for j = 1:n
if F(i,j) ~= 0 %由 i 发出的边,有向边的始点
W(i,k) = 1; %关联矩阵的始点值为1
W(j,k) = -1; %关联矩阵的终点值为-1
k = k+1;
end
end
end
elseif f == 1 %关联矩阵转换为邻接矩阵
m = size(F,2); %计算 F 的列数
n = size(F,1); %计算 F 的行数
W = zeros(n,n); % W 维度为 F 的顶点数的方阵
for i = 1:m
a = find(F(:,i) ~= 0); %找到有向边的两个顶点
if F(a(1),i) == 1
W(a(1),a(2)) = 1; %有向边由 a(1) 指向 a(2)
else
W(a(2),a(1)) = 1; %有向边由 a(2) 指向 a(1)
end
end
else
fprintf('please input the right value of f');
end
W;
end