如何循环通过一个图中的每个节点,并检查其程度- Matlab

jobtbby3  于 2022-11-30  发布在  Matlab
关注(0)|答案(1)|浏览(136)

我试图遍历无向图G中的所有节点,然后检查节点i的度是否为1。
我尝试了以下方法:

s = ["s1" "s1" "s2" "n1" "n2" "n3" "n4" "n5"];
t = ["s2" "s3" "s3" "s1" "s2" "s1" "s2" "s3"];
G = graph(s,t);
p = plot(G,'LineWidth',2);

edges = G.Edges
vertices = G.Nodes

for i = vertices(:, 1)
    if degree(G, i) == 1
        fprintf('%s has degree of 1', i)
    end 
end

但是,我得到了以下错误:
节点ID必须是数字节点索引或节点名称。
为什么会出现此错误?节点不是已经有名称了吗?
谢谢

b1uwtaje

b1uwtaje1#

正如@CrisLuengo提到的,我必须转置vertices。我还必须将其转换为数组,因为它显示为一个表。
下面是代码的工作版本。

s = ["s1" "s1" "s2" "n1" "n2" "n3" "n4" "n5"];
t = ["s2" "s3" "s3" "s1" "s2" "s1" "s2" "s3"];
 
G = graph(s,t);
p = plot(G,'LineWidth',2);
 
edges = G.Edges;
vertices = G.Nodes;
 
vertices_t =  transpose(table2array(vertices));
for i = vertices_t(:, :)
%     disp(degree(G, i))
    if degree(G, i) == 1
        fprintf('%s has degree of 1\n', i{1})
    end 
end

相关问题