Remove node and reconnect edges in graph

I have a node in a graph that acts as a sort of 'temporary connector' node. I'd like to remove that node and update the edges in the graph so that all of its immediate predecessors point to its immediate successors.
Example: I have a graph 1 > 2 > 3. I'd like to remove node 2 and end up with the graph 1 > 3.
I read several posts on removing nodes, but couldn't find a way to do what I want.

 採用された回答

Chunru
Chunru 2022 年 7 月 20 日

1 投票

s = [1 1 1 1 2 2 3 3 3 5 5];
t = [2 3 4 6 1 5 4 5 6 4 6];
names = string(1:6);
G = digraph(s, t, [], names);
h1 = plot(G);
% Remove node and add the eages
% node 1
G1 = G;
pre = predecessors(G1, 1);
suc = successors(G1, 1);
for i=1:length(pre)
for j=1:length(suc)
G1=addedge(G1, pre(i), suc(j));
end
end
G1 = rmnode(G1, 1); % remove the node 1 also remover the edges to 1
%G.Edges, G1.Edges
figure
h2 = plot(G1);
h2.XData = h1.XData(2:end);
h2.YData = h1.YData(2:end);

7 件のコメント

IrisL
IrisL 2022 年 7 月 20 日
Thanks for your answer. That helps a lot. I am wondering if this can also be done for nondirect graph. Removing node and reconnecting edges for graph without direction.
Chunru
Chunru 2022 年 7 月 20 日
編集済み: Chunru 2022 年 7 月 20 日
Yes. It can be definetely done with the same idea. Instead of finding the predecessors and successors, you need to find the neighbours. Then you need to add edges to each pairs of neighbours of the node to be removed (you may need to check if the edge to be added is already in the original graph).
IrisL
IrisL 2022 年 7 月 20 日
So I guess I can use one for loop instead of two for loop to do this.
Chunru
Chunru 2022 年 7 月 20 日
You may still need two for loops:
for i=1:length(nb) % nb: neighbors
for j=i+1:length(nb)
....
end
end
IrisL
IrisL 2022 年 7 月 21 日
Thanks. You mentioned checking if the edge to be added is alrready in the original graph. Do you have any suggestion on doing so (and potentially removing those duplicated edges)? I saw people using 'unique(sort(EdgeList,2),'rows')'. But I have the edges as a table instead of list.
Chunru
Chunru 2022 年 7 月 21 日
unique(G.Edges) should work for an Edge Table G.Edges
IrisL
IrisL 2022 年 7 月 21 日
I used unique(G.Edges.EndNodes) which returns a seperate cell with unique edges. However, this code does not remove duplicate edges from the graph. The number of the edges will not change and G.Edges remains the same.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeGraph and Network Algorithms についてさらに検索

製品

リリース

R2020b

質問済み:

2022 年 7 月 19 日

コメント済み:

2022 年 7 月 21 日

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by