Join Subgraphs into a new Graph
显示 更早的评论
Is there a way or function in Matlab to merge/connect/join a number of Subgraphs into a new Graph?
The following code shows that starting from a Graph, we can extract Subgraphs. What I am looking for is a function to go to the opposite direction, i.e. given a set of (likely overlapping) Subgraphs, join/conncet/nerge them into a new Graph. Is it possible somehow?
clear all; clc; close all;
% Creata a Graph
s = [1 1 1 3 3 6 7 8 9 10 4 12 13 5 15 16 17 18 19 19 20 20 17 24 25 4 27 28 29];
t = [2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30];
G = graph(s,t);
% Node ID: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
G.Nodes.X = [2 1 3 2 4 4 5 4 5 4 5 1 3 3 5 6 7 6 8 7 9 8 9 8 9 10 1 1 0 1]';
G.Nodes.Y = [2 1 3 9 3 5 8 12 13 18 21 15 18 21 0 2 8 12 15 20 10 22 18 5 4 4 5 8 12 23]';
% Extract the Subgraphs from the "Original Graph"
Gpath{1} = subgraph(G,shortestpath(G,4,14));
Gpath{2} = subgraph(G,shortestpath(G,4,26));
Gpath{3} = subgraph(G,shortestpath(G,4,30));
Gpath{4} = subgraph(G,shortestpath(G,3,10));
Gpath{5} = subgraph(G,shortestpath(G,3,28));
Gpath{6} = subgraph(G,shortestpath(G,3,21));
Gpath{7} = subgraph(G,shortestpath(G,17,12));
Gpath{8} = subgraph(G,shortestpath(G,17,23));
Gpath{9} = subgraph(G,shortestpath(G,17,26));
% Figure
hold on
p(1) = plot(G,'XData',G.Nodes.X,'YData',G.Nodes.Y,'LineWidth',1,'EdgeColor','k','NodeColor','k');
p(1).DisplayName = 'Original Graph';
for i = 1:9
p(2) = plot(Gpath{i},'XData',Gpath{i}.Nodes.X,'YData',Gpath{i}.Nodes.Y,'EdgeColor','y','NodeColor','y');
p(2).NodeLabel = {};
p(2).EdgeAlpha = 1;
p(2).LineWidth = 5;
p(2).DisplayName = sprintf('Subgraph %d',i);
end
legend('Location','eastoutside')

采纳的回答
更多回答(1 个)
G1 = graph(randi(10, 20, 1), randi(10, 20, 1));
G2 = graph(randi(10, 20, 1), randi(10, 20, 1));
Here I have two random graphs, each with 10 nodes and up to 20 edges.
subplot(1, 2, 1)
plot(G1)
title("G1")
subplot(1, 2, 2)
plot(G2)
title("G2")
When you say you want to join these, how do you want to join them? Which nodes in G1 should connect to nodes in G2? Or do you just want to join them into a forest, where each node in G2 is renumbered to avoid conflict with the nodes that already exist in G1?
G3 = G1;
G3 = addedge(G3, G2.Edges+numnodes(G1));
figure
plot(G3)
title("G3")
Or do you want each node in the joined graph to connect to any node that it was connected to in either G1 or G2?
G4 = G1;
G4 = addedge(G4, G2.Edges);
figure
plot(G4)
title("G4")
Also, FYI, rather than plotting each graph anew I'd consider using highlight to highlight them in the plot of the existing graph.
类别
在 帮助中心 和 File Exchange 中查找有关 App Building 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!








