%% Modify Nodes and Edges of Existing Graph
% This example shows how to access and modify the nodes and/or edges in a graph or digraph object using the addedge, rmedge, addnode, rmnode, findedge, findnode, and subgraph functions.
%% Add Nodes
% Create a graph with four nodes and four edges. The corresponding elements in s and t specify the end nodes of each graph edge.

s = [1 1 1 2];
t = [2 3 4 3];
G = graph(s,t)

%
% View the edge list of the graph.

G.Edges

%
% Use addnode to add five nodes to the graph. This command adds five disconnected nodes with node IDs 5, 6, 7, 8, and 9.

G = addnode(G,5)

%
%% Remove Nodes
% Use rmnode to remove nodes 3, 5, and 6 from the graph. All edges connected to one of the removed nodes also are removed. The remaining six nodes in the graph are renumbered to reflect the new number of nodes.

G = rmnode(G,[3 5 6])

%
%% Add Edges
% Use addedge to add two edges to G. The first edge is between node 1 and node 5, and the second edge is between node 2 and node 5. This command adds two new rows to G.Edges.

G = addedge(G,[1 2],[5 5])

%
%% Remove Edges
% Use rmedge to remove the edge between node 1 and node 3. This command removes a row from G.Edges.

G = rmedge(G,1,3)

%
%% Determine Edge Index
% Determine the edge index for the edge between nodes 1 and 5. The edge index, ei, is a row number in G.Edges.

ei = findedge(G,1,5)

%
%% Determine Node Index
% Add node names to the graph, and then determine the node index for node 'd'. The numeric node index, ni, is a row number in G.Nodes. You can use both ni and the node name, 'd', to refer to the node when using other graph functions, like shortestpath.

G.Nodes.Name = {'a' 'b' 'c' 'd' 'e' 'f'}';
ni = findnode(G,'d')

%
%% Extract Subgraph
% Use subgraph to extract a piece of the graph containing only two nodes.

H = subgraph(G,[1 2])

%
% View the edge list of the subgraph.

H.Edges

%
%% Modify Node and Edge Tables with Variables Editor
% The node and edge information for a graph object is contained in two properties: Nodes and Edges. Both of these properties are tables containing variables to describe the attributes of the nodes and edges in the graph. Since Nodes and Edges are both tables, you can use the Variables editor to interactively view or edit the tables. You cannot add or remove nodes or edges using the Variables editor, and you also cannot edit the EndNodes property of the Edges table. The Variables editor is useful for managing extra node and edge attributes in the Nodes and Edges tables. For more information, see Create and Edit Variables.
% Copyright 2012 The MathWorks, Inc.