Remove duplicate edges of undirected graph

7 views (last 30 days)
I am trying to remove duplicated edges of a garph.
I was able to get the unique edges by using
unique(G2.Edges.EndNodes)
However, this code only returns the unique edges without updating the G2.Edges table nor removing edges from the graph.
Any suggestion will be appreciated. Thanks.
My edges table look like this:

Accepted Answer

Steven Lord
Steven Lord on 21 Jul 2022
Call simplify on your multigraph (you can tell if your graph or digraph is a multigraph using ismultigraph) to convert it to a simple graph.
s = [1 1 1 1 1 2 2 3 3 3 3 5 5];
t = [2 3 4 4 6 1 5 4 4 5 6 4 6];
names = string(1:6);
multiGraph = graph(s, t);
check = ismultigraph(multiGraph)
check = logical
1
simpleGraph = simplify(multiGraph);
Let's compare how they look.
figure
h = plot(multiGraph);
title('multigraph');
figure
% Plot the simple graph with the vertices in the same location
% as the vertices in the multigraph
plot(simpleGraph, 'XData', h.XData, 'YData', h.YData)
title('simplegraph')

More Answers (1)

Chunru
Chunru on 21 Jul 2022
% A graph with duplicated edges
s = [1 1 1 1 1 2 2 3 3 3 3 5 5];
t = [2 3 4 4 6 1 5 4 4 5 6 4 6];
names = string(1:6);
G = graph(s, t);
% A new graph with unique edges
G.Edges;
G1 = graph(unique(G.Edges)); % Create a new graph based on the unique edge rather than updating
subplot(121);
h1 = plot(G);
subplot(122)
h2 = plot(G1);
  3 Comments
Chunru
Chunru on 21 Jul 2022
If you have node names specified, such as:
% A graph with duplicated edges
s = [1 1 1 1 1 2 2 3 3 3 3 5 5];
t = [2 3 4 4 6 1 5 4 4 5 6 4 6];
names = string(1:6);
G = graph(s, t, [], names);
% A new graph with unique edges
G.Edges % EndNodes
ans = 13×1 table
EndNodes ______________ {'1'} {'2'} {'1'} {'2'} {'1'} {'3'} {'1'} {'4'} {'1'} {'4'} {'1'} {'6'} {'2'} {'5'} {'3'} {'4'} {'3'} {'4'} {'3'} {'5'} {'3'} {'6'} {'4'} {'5'} {'5'} {'6'}
% Using string array for unique (rather cell array)
newEdges = cellstr(unique(string(G.Edges.EndNodes), 'row'));
EdgeTable = table(newEdges, 'VariableNames', {'EndNodes'});
G1 = graph(EdgeTable); % Create a new graph based on the unique edge rather than updating
subplot(121);
h1 = plot(G);
subplot(122)
h2 = plot(G1);
IrisL
IrisL on 21 Jul 2022
Thanks. This is helpful as well!

Sign in to comment.

Categories

Find more on Graph and Network Algorithms in Help Center and File Exchange

Products


Release

R2020b

Community Treasure Hunt

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

Start Hunting!