如何用循环标记图形边缘?

How to label graph edges with a loop?

我正在使用 for 循环在我的绘图上添加更多节点和边。但是,当我在新边上添加标签时,旧标签将被删除。我不知道如何保留旧的边缘标签,也不知道如何存储 labeledge.

的结果

这是我目前得到的。

for r = 1: 10
    for j = 1:10
        H = addnode(P,nodeName{r}{j});
        P = addedge(H, s{r}{j}, t{r}{j}, w{r}{j});
        figure;
        hold on;
        h = plot(P);
        labeledge(h,s{r}{j},t{r}{j},labelText{r}{j})
    end
end

每次在新的情节中,我只能看到最新的一组标签,而旧的标签已经消失了。理想情况下,我很想 hold on labeledge 的结果,但 hold on 不能这样做。我需要在循环的每个步骤中显示标签,因此添加另一个整体 labeledge 不是我理想的解决方案。任何提示将不胜感激。

编辑: 我的所有变量都是元胞数组中大小不同的多个元胞。我使用 for 循环来帮助从单元格中提取向量,因为我不知道如何将来自此类单元格数组等的所有级别的信息插入到 addNode 函数中。

尝试从 FOR 循环中删除 'figure;' 命令并尝试查看是否有效。

您代码中的主要问题是您不断地绘制图表。这是没有必要的。相反,使用一个循环来创建图形对象 (G),然后一次绘制所有对象,然后使用另一个循环来标记图形:

P = graph;
for r = 1: 10
    for j = 1:10
        P = addedge(P, s{r}{j}, t{r}{j}, w{r}{j});
    end
end
h = plot(P);
for r = 1: 10
    for j = 1:10
        labeledge(h,s{r}{j},t{r}{j},labelText{r}{j})
    end
end

如果您希望在每次迭代时绘制图表,您可以使用 subgraph

for k = 1:height(P.Nodes)
    H = subgraph(P,1:k);
    figure;
    h = plot(H);
    c = 1;
    out = false;
    for r = 1: 10
        if ~out
            for j = 1:10
                if c < k
                    labeledge(h,c,labelText{r}{j})
                else
                    out = true;
                    break
                end
                c = c+1;
            end
        else
            break
        end
    end
end

除此之外,你应该知道 (from Matlab documentation):

For the best performance, construct graphs all at once using a single call to graph. Adding nodes or edges in a loop can be slow for large graphs.

此外,无论上述建议如何,为了更轻松地处理数据,您应该首先将单元格转换为数组。如果您的元胞数组在每个元胞中包含不同数量的元素,那么最好将其全部折叠成一列:

C = [s{:}]; % and the same for t and w
while any(cellfun(@iscell,C))
    C = vertcat(C{:});
end
C = cellfun(@(x) x(:),C,'UniformOutput', false);
S = vertcat(C{:});

Labels = [labelText{:}]; % and the same nodeName
while any(cellfun(@iscell,Labels))
    Labels = vertcat(Labels{:});
end