www.gusucode.com > matlab 案例源码 matlab代码程序 > matlab/AddGraphNodeNamesEdgeWeightsAndOtherAttributesExample.m

    %% Add Graph Node Names, Edge Weights, and Other Attributes
% This example shows how to add attributes to the nodes and edges in graphs
% created using |graph| and |digraph|. You can specify node names or edge
% weights when you originally call |graph| or |digraph| to create a graph.
% However, this example shows how to add attributes to a graph after it has
% been created.

%% Create Graph
% Create a directed graph. The corresponding elements in |s| and |t| define
% the source and target nodes of each edge in the graph.
s = [1 1 2 2 3];
t = [2 4 3 4 4];
G = digraph(s,t)

%% Add Node Names
% Add node names to the graph by adding the variable, |Name|, to the
% |G.Nodes| table. The |Name| variable must be an |N|-by-1 cell array of
% character vectors, where |N = numnodes(G)|. It is important to use the
% |Name| variable when adding node names, as this variable name is treated
% specially by some graph functions.
G.Nodes.Name = {'First' 'Second' 'Third' 'Fourth'}';

%%
% View the new |Nodes| table.
G.Nodes

%%
% Use table indexing to view the names of nodes 1 and 4.
G.Nodes.Name([1 4])

%% Add Edge Weights
% Add edge weights to the graph by adding the variable, |Weight|, to the
% |G.Edges| table. The |Weight| variable must be an |M|-by-1 numeric
% vector, where |M = numedges(G)|. It is important to use the |Weight|
% variable when adding edge weights, as this variable name is treated
% specially by some graph functions.
G.Edges.Weight = [10 20 30 40 50]';

%%
% View the new |Edges| table.
G.Edges

%%
% Use table indexing to view the first and third rows of |G.Edges|.
G.Edges([1 3],:)

%% Add Custom Attributes
% In principle you can add any variable to |G.Nodes| and |G.Edges| that
% defines an attribute of the graph nodes or edges. Adding custom
% attributes can be useful, since functions like |subgraph| and
% |reordernodes| preserve the graph attributes.
%
% For example, add a variable named |Power| to |G.Edges| to indicate
% whether each edge is |'on'| or |'off'|.
G.Edges.Power = {'on' 'on' 'on' 'off' 'off'}';
G.Edges

%%
% Add a variable named |Size| to |G.Nodes| to indicate the physical size of
% each node.
G.Nodes.Size = [10 20 10 30]';
G.Nodes

%% Modify Tables with Variables Editor
% Since |Nodes| and |Edges| are both tables, you can use the Variables
% editor to interactively view or edit the tables. For more information,
% see <docid:matlab_env.bvdl_z8>.

%% Label Nodes and Edges of Graph Plot
% When you plot a graph, you can use the variables in |G.Nodes| and
% |G.Edges| to label the graph nodes and edges. This practice is
% convenient, since these variables are already guaranteed to have the
% correct number of elements.
%
% Plot the graph and label the edges using the |Power| variable in
% |G.Edges|. Label the nodes using the |Size| variable in |G.Nodes|.
p = plot(G,'EdgeLabel',G.Edges.Power,'NodeLabel',G.Nodes.Size)