%% Remove Multiple Edges from Graph
% Use ismultigraph to determine whether a graph needs to be simplified.
%
% It is common to encounter duplicate edges when you create an empty graph and programmatically add edges to it with addedge. The data used for the edges needs to be unique to avoid duplicates.
% To demonstrate this, create an empty graph and a matrix with two columns of random numbers. Since the random numbers are only between 1 and 5, this data produces multiple edges.

G = graph;
rng default % for reproducibility
X = randi(5,15,2)

%
% Instead of cleaning the source data to ensure the rows are unique, add all of the edges to the graph. Plot the graph for reference.

G = addedge(G,X(:,1),X(:,2));
plot(G)

% Test to see if the graph is a multigraph and, if it is, use simplify to remove repeated edges and self-loops.

if ismultigraph(G)
    G = simplify(G);
end

%
% Plot the resulting graph.

plot(G)

% Copyright 2012 The MathWorks, Inc.