Main Content

graph

Graph with undirected edges

Description

graph objects represent undirected graphs, which have direction-less edges connecting the nodes. After you create a graph object, you can learn more about the graph by using object functions to perform queries against the object. For example, you can add or remove nodes or edges, determine the shortest path between two nodes, or locate a specific node or edge.

G = graph([1 1], [2 3]);
e = G.Edges
G = addedge(G,2,3)
G = addnode(G,4)
plot(G)

Creation

Description

example

G = graph creates an empty undirected graph object, G, which has no nodes or edges.

example

G = graph(A) creates a graph using a square, symmetric adjacency matrix, A.

  • For logical adjacency matrices, the graph has no edge weights.

  • For nonlogical adjacency matrices, the graph has edge weights. The location of each nonzero entry in A specifies an edge for the graph, and the weight of the edge is equal to the value of the entry. For example, if A(2,1) = 10, then G contains an edge between node 2 and node 1 with a weight of 10.

example

G = graph(A,nodenames) additionally specifies node names. The number of elements in nodenames must be equal to size(A,1).

G = graph(A,NodeTable) specifies node names (and possibly other node attributes) using a table, NodeTable. The table must have the same number of rows as A. Specify node names using the table variable Name.

example

G = graph(A,___,type) specifies a triangle of the adjacency matrix to use in constructing the graph. You must specify A and optionally can specify nodenames or NodeTable. To use only the upper or lower triangle of A to construct the graph, type can be either 'upper' or 'lower'.

example

G = graph(A,___,'omitselfloops') ignores the diagonal elements of A and returns a graph without any self-loops. You can use any of the input argument combinations in previous syntaxes.

example

G = graph(s,t) specifies graph edges (s,t) in node pairs. s and t can specify node indices or node names. graph sorts the edges in G first by source node, and then by target node. If you have edge properties that are in the same order as s and t, use the syntax G = graph(s,t,EdgeTable) to pass in the edge properties so that they are sorted in the same manner in the resulting graph.

example

G = graph(s,t,weights) also specifies edge weights with the array weights.

example

G = graph(s,t,weights,nodenames) specifies node names using the cell array of character vectors or string array, nodenames. s and t cannot contain node names that are not in nodenames.

G = graph(s,t,weights,NodeTable) specifies node names (and possibly other node attributes) using a table, NodeTable. Specify node names using the Name table variable. s and t cannot contain node names that are not in NodeTable.

example

G = graph(s,t,weights,num) specifies the number of nodes in the graph with the numeric scalar num.

G = graph(s,t,___,'omitselfloops') does not add any self-loops to the graph. That is, any k that satisfies s(k) == t(k) is ignored. You can use any of the input argument combinations in previous syntaxes.

G = graph(s,t,EdgeTable,___) uses a table to specify edge attributes instead of specifying weights. The EdgeTable input must be a table with a row for each corresponding pair of elements in s and t. Specify edge weights using the table variable Weight.

example

G = graph(EdgeTable) uses the table EdgeTable to define the graph. With this syntax, the first variable in EdgeTable must be named EndNodes, and it must be a two-column array defining the edge list of the graph.

example

G = graph(EdgeTable,NodeTable) additionally specifies the names (and possibly other attributes) of the graph nodes using a table, NodeTable.

G = graph(EdgeTable,___,'omitselfloops') does not add self-loops to the graph. That is, any k that satisfies EdgeTable.EndNodes(k,1) == EdgeTable.EndNodes(k,2) is ignored. You must specify EdgeTable and optionally can specify NodeTable.

Input Arguments

expand all

Adjacency matrix, specified as a full or sparse, numeric matrix. The entries in A specify the network of connections (edges) between the nodes of the graph. The location of each nonzero entry in A specifies an edge between two nodes. The value of that entry provides the edge weight. A logical adjacency matrix results in an unweighted graph.

Nonzero entries on the main diagonal of A specify self-loops, or nodes that are connected to themselves with an edge. Use the 'omitselfloops' input option to ignore diagonal entries.

A must be symmetric unless the type input is specified. Use issymmetric to confirm matrix symmetry. For triangular adjacency matrices, specify type to use only the upper or lower triangle.

Example: A = [0 1 5; 1 0 0; 5 0 0] describes a graph with three nodes and two edges. The edge between node 1 and node 2 has a weight of 1, and the edge between node 1 and node 3 has a weight of 5.

Data Types: single | double | logical

Node names, specified as a cell array of character vectors or string array. nodenames must have length equal to numnodes(G) so that it contains a nonempty, unique name for each node in the graph.

Example: G = graph(A,{'n1','n2','n3'}) specifies three node names for a 3-by-3 adjacency matrix, A.

Data Types: cell | string

Type of adjacency matrix, specified as either 'upper' or 'lower'.

Example: G = graph(A,'upper') uses only the upper triangle of A to construct the graph, G.

Node pairs, specified as node indices or node names. graph creates edges between the corresponding nodes in s and t, which must both be numeric, or both be character vectors, cell arrays of character vectors, string arrays, or categorical arrays. In all cases, s and t must have the same number of elements.

  • If s and t are numeric, then they correspond to indices of graph nodes. Numeric node indices must be positive integers greater than or equal to 1.

  • If s and t are character vectors, cell arrays of character vectors, or string arrays, then they specify names for the nodes. The Nodes property of the graph is a table containing a Name variable with the node names, G.Nodes.Name.

  • If s and t are categorical arrays, then the categories in s and t are used as the node names in the graph. This can include categories that are not elements in s or t.

  • If s and t specify multiple edges between the same two nodes, then the result is a multigraph.

This table shows the different ways to refer to one or more nodes either by their numeric node indices or by their node names.

FormSingle NodeMultiple Nodes
Node index

Scalar

Example: 1

Vector

Example: [1 2 3]

Node name

Character vector

Example: 'A'

Cell array of character vectors

Example: {'A' 'B' 'C'}

String scalar

Example: "A"

String array

Example: ["A" "B" "C"]

Categorical array

Example: categorical("A")

Categorical array

Example: categorical(["A" "B" "C"])

Example: G = graph([1 2 3],[2 4 5]) creates a graph with five nodes and three edges.

Example: G = graph({'Boston' 'New York' 'Washington D.C.'},{'New York' 'New Jersey' 'Pittsburgh'}) creates a graph with five named nodes and three edges.

Edge weights, specified as a scalar, vector, matrix, or multidimensional array. weights must be a scalar or an array with the same number of elements as s and t.

graph stores the edge weights as a Weight variable in the G.Edges property table. To add or change weights after creating a graph, you can modify the table variable directly, for example, G.Edges.Weight = [25 50 75]'.

If you specify weights as an empty array [], then it is ignored.

Example: G = graph([1 2],[2 3],[100 200]) creates a graph with three nodes and two edges. The edges have weights of 100 and 200.

Data Types: single | double

Number of graph nodes, specified as a positive scalar integer. num must be greater than or equal to the largest elements in s and t.

Example: G = graph([1 2],[2 3],[],5) creates a graph with three connected nodes and two isolated nodes.

Table of edge information. If you do not specify s and t, then the first variable in EdgeTable is required to be a two-column matrix, cell array of character vectors, or string array called EndNodes that defines the graph edges. For edge weights, use the variable Weight, since this table variable name is used by some graph functions. If there is a variable Weight, then it must be a numeric column vector. See table for more information on constructing a table.

After creating a graph, query the edge information table using G.Edges.

Example: EdgeTable = table([1 2; 2 3; 3 5; 4 5],'VariableNames',{'EndNodes'})

Data Types: table

Table of node information. NodeTable can contain any number of variables to describe attributes of the graph nodes. For node names, use the variable Name, since this variable name is used by some graph functions. If there is a variable Name, then it must be a cell array of character vectors or string array specifying a unique name in each row. See table for more information on constructing a table.

After the graph is created, query the node information table using G.Nodes.

Example: NodeTable = table({'a'; 'b'; 'c'; 'd'},'VariableNames',{'Name'})

Data Types: table

Properties

expand all

Edges of graph, returned as a table. By default this is an M-by-1 table, where M is the number of edges in the graph. The edge list in G.Edges.EndNodes is sorted first by source node, and then by target node.

  • To add new edge properties to the graph, create a new variable in the Edges table.

  • To add or remove edges from the graph, use the addedge or rmedge object functions.

Example: G.Edges returns a table listing the edges in the graph

Example: G.Edges.Weight returns a numeric vector of the edge weights.

Example: G.Edges.Weight = [10 20 30 55]' specifies new edge weights for the graph.

Example: G.Edges.NormWeight = G.Edges.Weight/sum(G.Edges.Weight) adds a new edge property to the table containing the normalized weights of the edges.

Data Types: table

Nodes of graph, returned as a table. By default this is an empty N-by-0 table, where N is the number of nodes in the graph.

  • To add new node properties to the graph, create a new variable in the Nodes table.

  • To add or remove nodes from the graph, use the addnode or rmnode object functions.

Example: G.Nodes returns a table listing the node properties of the graph. This table is empty by default.

Example: G.Nodes.Names = {'Montana', 'New York', 'Washington', 'California'}' adds node names to the graph by adding the variable Names to the Nodes table.

Example: G.Nodes.WiFi = logical([1 0 0 1 1]') adds the variable WiFi to the Nodes table. This property specifies that certain airports have wireless internet coverage.

Data Types: table

Object Functions

expand all

addedgeAdd new edge to graph
rmedgeRemove edge from graph
addnodeAdd new node to graph
rmnodeRemove node from graph
findedgeLocate edge in graph
findnodeLocate node in graph
numedgesNumber of edges in graph
numnodesNumber of nodes in graph
edgecountNumber of edges between two nodes
reordernodesReorder graph nodes
subgraphExtract subgraph
centralityMeasure node importance
conncompConnected graph components
biconncompBiconnected graph components
bctreeBlock-cut tree graph
isisomorphicDetermine whether two graphs are isomorphic
isomorphismCompute isomorphism between two graphs
ismultigraphDetermine whether graph has multiple edges
simplifyReduce multigraph to simple graph
bfsearchBreadth-first graph search
dfsearchDepth-first graph search
shortestpathShortest path between two single nodes
shortestpathtreeShortest path tree from node
distancesShortest path distances of all node pairs
maxflowMaximum flow in graph
minspantreeMinimum spanning tree of graph
allpathsFind all paths between two graph nodes
hascyclesDetermine whether graph contains cycles
allcyclesFind all cycles in graph
cyclebasisFundamental cycle basis of graph
adjacencyGraph adjacency matrix
incidenceGraph incidence matrix
laplacianGraph Laplacian matrix
degreeDegree of graph nodes
neighborsNeighbors of graph node
nearestNearest neighbors within radius
outedgesOutgoing edges from node
plotPlot graph nodes and edges

Examples

collapse all

Create a graph object with three nodes and two edges. One edge is between node 1 and node 2, and the other edge is between node 1 and node 3.

G = graph([1 1],[2 3])
G = 
  graph with properties:

    Edges: [2x1 table]
    Nodes: [3x0 table]

View the edge table of the graph.

G.Edges
ans=2×1 table
    EndNodes
    ________

     1    2 
     1    3 

Add node names to the graph, and then view the new node and edge tables. The end nodes of each edge are now expressed using their node names.

G.Nodes.Name = {'A' 'B' 'C'}';
G.Nodes
ans=3×1 table
    Name 
    _____

    {'A'}
    {'B'}
    {'C'}

G.Edges
ans=2×1 table
       EndNodes   
    ______________

    {'A'}    {'B'}
    {'A'}    {'C'}

You can add or modify extra variables in the Nodes and Edges tables to describe attributes of the graph nodes or edges. However, you cannot directly change the number of nodes or edges in the graph by modifying these tables. Instead, use the addedge, rmedge, addnode, or rmnode functions to modify the number of nodes or edges in a graph.

For example, add an edge to the graph between nodes 2 and 3 and view the new edge list.

G = addedge(G,2,3)
G = 
  graph with properties:

    Edges: [3x1 table]
    Nodes: [3x1 table]

G.Edges
ans=3×1 table
       EndNodes   
    ______________

    {'A'}    {'B'}
    {'A'}    {'C'}
    {'B'}    {'C'}

Create a symmetric adjacency matrix, A, that creates a complete graph of order 4. Use a logical adjacency matrix to create a graph without weights.

A = ones(4) - diag([1 1 1 1])
A = 4×4

     0     1     1     1
     1     0     1     1
     1     1     0     1
     1     1     1     0

G = graph(A~=0)
G = 
  graph with properties:

    Edges: [6x1 table]
    Nodes: [4x0 table]

View the edge list of the graph.

G.Edges
ans=6×1 table
    EndNodes
    ________

     1    2 
     1    3 
     1    4 
     2    3 
     2    4 
     3    4 

Create an upper triangular adjacency matrix.

A = triu(magic(4))
A = 4×4

    16     2     3    13
     0    11    10     8
     0     0     6    12
     0     0     0     1

Create a graph with named nodes using the adjacency matrix. Specify 'omitselfloops' to ignore the entries on the diagonal of A, and specify type as 'upper' to indicate that A is upper-triangular.

names = {'alpha' 'beta' 'gamma' 'delta'};
G = graph(A,names,'upper','omitselfloops')
G = 
  graph with properties:

    Edges: [6x2 table]
    Nodes: [4x1 table]

View the edge and node information.

G.Edges
ans=6×2 table
           EndNodes           Weight
    ______________________    ______

    {'alpha'}    {'beta' }       2  
    {'alpha'}    {'gamma'}       3  
    {'alpha'}    {'delta'}      13  
    {'beta' }    {'gamma'}      10  
    {'beta' }    {'delta'}       8  
    {'gamma'}    {'delta'}      12  

G.Nodes
ans=4×1 table
      Name   
    _________

    {'alpha'}
    {'beta' }
    {'gamma'}
    {'delta'}

Create and plot a cube graph using a list of the end nodes of each edge.

s = [1 1 1 2 2 3 3 4 5 5 6 7];
t = [2 4 8 3 7 4 6 5 6 8 7 8];
G = graph(s,t)
G = 
  graph with properties:

    Edges: [12x1 table]
    Nodes: [8x0 table]

plot(G)

Figure contains an axes object. The axes object contains an object of type graphplot.

Create and plot a cube graph using a list of the end nodes of each edge. Specify node names and edge weights as separate inputs.

s = [1 1 1 2 2 3 3 4 5 5 6 7];
t = [2 4 8 3 7 4 6 5 6 8 7 8];
weights = [10 10 1 10 1 10 1 1 12 12 12 12];
names = {'A' 'B' 'C' 'D' 'E' 'F' 'G' 'H'};
G = graph(s,t,weights,names)
G = 
  graph with properties:

    Edges: [12x2 table]
    Nodes: [8x1 table]

plot(G,'EdgeLabel',G.Edges.Weight)

Figure contains an axes object. The axes object contains an object of type graphplot.

Create a weighted graph using a list of the end nodes of each edge. Specify that the graph should contain a total of 10 nodes.

s = [1 1 1 1 1];
t = [2 3 4 5 6];
weights = [5 5 5 6 9];
G = graph(s,t,weights,10)
G = 
  graph with properties:

    Edges: [5x2 table]
    Nodes: [10x0 table]

Plot the graph. The extra nodes are disconnected from the primary connected component.

plot(G)

Figure contains an axes object. The axes object contains an object of type graphplot.

Create an empty graph object, G.

G = graph;

Add three nodes and three edges to the graph. The corresponding entries in s and t define the end nodes of the graph edges. addedge automatically adds the appropriate nodes to the graph if they are not already present.

s = [1 2 1];
t = [2 3 3];
G = addedge(G,s,t)
G = 
  graph with properties:

    Edges: [3x1 table]
    Nodes: [3x0 table]

View the edge list. Each row describes an edge in the graph.

G.Edges
ans=3×1 table
    EndNodes
    ________

     1    2 
     1    3 
     2    3 

For the best performance, construct graphs all at once using a single call to graph. Adding nodes or edges in a loop can be slow for large graphs.

Create an edge table that contains the variables EndNodes, Weight, and Code. Then create a node table that contains the variables Name and Country. The variables in each table specify properties of the graph nodes and edges.

s = [1 1 1 2 3];
t = [2 3 4 3 4];
weights = [6 6.5 7 11.5 17]';
code = {'1/44' '1/49' '1/33' '44/49' '49/33'}';
EdgeTable = table([s' t'],weights,code, ...
    'VariableNames',{'EndNodes' 'Weight' 'Code'})
EdgeTable=5×3 table
    EndNodes    Weight      Code   
    ________    ______    _________

     1    2         6     {'1/44' }
     1    3       6.5     {'1/49' }
     1    4         7     {'1/33' }
     2    3      11.5     {'44/49'}
     3    4        17     {'49/33'}

names = {'USA' 'GBR' 'DEU' 'FRA'}';
country_code = {'1' '44' '49' '33'}';
NodeTable = table(names,country_code,'VariableNames',{'Name' 'Country'})
NodeTable=4×2 table
     Name      Country
    _______    _______

    {'USA'}    {'1' } 
    {'GBR'}    {'44'} 
    {'DEU'}    {'49'} 
    {'FRA'}    {'33'} 

Create a graph using the node and edge tables. Plot the graph using the country codes as node and edge labels.

G = graph(EdgeTable,NodeTable);
plot(G,'NodeLabel',G.Nodes.Country,'EdgeLabel',G.Edges.Code)

Figure contains an axes object. The axes object contains an object of type graphplot.

Extended Capabilities

Thread-Based Environment
Run code in the background using MATLAB® backgroundPool or accelerate code with Parallel Computing Toolbox™ ThreadPool.

Version History

Introduced in R2015b

expand all