# Documentation

### This is machine translation

Translated by
Mouseover text to see original. Click the button below to return to the English version of the page.

Note: This page has been translated by MathWorks. Please click here
To view all translated materials including this page, select Japan from the country navigator on the bottom of this page.

# 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

### Syntax

``G = graph``
``G = graph(A)``
``G = graph(A,nodenames)``
``G = graph(A,NodeTable)``
``G = graph(A,___,type)``
``G = graph(A,___,'OmitSelfLoops')``
``G = graph(s,t)``
``G = graph(s,t,weights)``
``G = graph(s,t,weights,nodenames)``
``G = graph(s,t,weights,NodeTable)``
``G = graph(s,t,weights,num)``
``G = graph(s,t,___,'OmitSelfLoops')``
``G = graph(s,t,EdgeTable,___)``
``G = graph(EdgeTable)``
``G = graph(EdgeTable,NodeTable)``
``G = graph(EdgeTable,___,'OmitSelfLoops')``

### Description

example

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

example

````G = graph(A)` creates a weighted graph using a square, symmetric adjacency matrix, `A`. 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 be numeric, character vectors, or cell arrays of character vectors with the same number of elements.```

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, `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. `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`

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 scalars, vectors, matrices, multidimensional arrays, character vectors, or cell arrays of character vectors. `graph` creates edges between the corresponding nodes in `s` and `t`, which must both be numeric, or both be character vectors or cell arrays of character vectors. In each case, `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 or cell arrays of character vectors, 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`.

• `s` and `t` cannot specify duplicate edges. For undirected graphs, ```graph([1 2],[2 1])``` and `graph([1 1],[2 2])` both specify a duplicate edge between node 1 and node 2.

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 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 column cell array of nonempty, unique character vectors. 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`

### Output Arguments

expand all

Undirected graph, returned as a `graph` object. For more information, see `graph`.

## 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.

• 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

 `addedge` Add new edge to graph `rmedge` Remove edge from graph `addnode` Add new node to graph `rmnode` Remove node from graph `findedge` Locate edge in graph `findnode` Locate node in graph `numedges` Number of edges in graph `numnodes` Number of nodes in graph `reordernodes` Reorder graph nodes `subgraph` Extract subgraph
 `bfsearch` Breadth-first graph search `dfsearch` Depth-first graph search `centrality` Measure node importance `conncomp` Connected graph components `biconncomp` Biconnected graph components `bctree` Block-cut tree graph `maxflow` Maximum flow in graph `minspantree` Minimum spanning tree of graph `isisomorphic` Determine whether two graphs are isomorphic `isomorphism` Compute equivalence relation between two graphs
 `shortestpath` Shortest path between two single nodes `shortestpathtree` Shortest path tree from node `distances` Shortest path distances of all node pairs
 `adjacency` Graph adjacency matrix `incidence` Graph incidence matrix `laplacian` Graph Laplacian matrix
 `degree` Degree of graph nodes `neighbors` Neighbors of graph node `nearest` Nearest neighbors within radius
 `plot` Plot graph nodes and edges

## Examples

expand 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=2x1 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=3x1 table Name ____ 'A' 'B' 'C' ```
`G.Edges`
```ans=2x1 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=3x1 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 = 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=6x1 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 = 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=6x2 table EndNodes Weight __________________ ______ 'alpha' 'beta' 2 'alpha' 'gamma' 3 'alpha' 'delta' 13 'beta' 'gamma' 10 'beta' 'delta' 8 'gamma' 'delta' 12 ```
`G.Nodes`
```ans=4x1 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)`

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)`

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)`

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=3x1 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=5x3 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=4x2 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)```

#### Introduced in R2015b

Was this topic helpful?

#### The Manager's Guide to Solving the Big Data Conundrum

Download white paper