You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Matlab遍历无向图节点检查度时出现节点ID错误的原因

问题分析与解决

错误原因

你代码里的vertices = G.Nodes得到的是一个table对象,vertices(:, 1)返回的是table的第一列(仍然是table类型),而degree函数只接受两种输入:数值类型的节点索引,或者字符串类型的节点名称。直接把table列传入degree,函数无法识别这种类型,就会抛出Node IDs must be numeric node indices or node names.的错误。

修正代码

方案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.Name; % 提取名称列的字符串数组

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

方案2:通过数值索引遍历节点

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 = 1:height(vertices)
    node_name = vertices.Name(i);
    if degree(G, node_name) == 1
        fprintf('%s has degree of 1\n', node_name)
    end 
end

两种方案都能正确遍历节点并检查度是否为1,方案1更简洁,直接操作字符串数组;方案2通过索引遍历,适合需要同时处理节点索引和名称的场景。

内容的提问来源于stack exchange,提问作者Emma

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 21:50:22