graph

Creates an undirected graph from edges or an adjacency matrix.

Category: Mathematics > Graph and Network Algorithms

Syntax

G = graph(s, t)

Edge k joins nodes s(k) and t(k).

G = graph(s, t, w)

Also gives the edges weights w.

G = graph(s, t, w, names)

Names the nodes.

G = graph(A)

Builds the graph from a symmetric adjacency matrix; nonzero entries are edges and their values are weights.

Description

A graph is a set of nodes joined by edges, and in a graph the edges have no direction. The number of nodes is the largest index used. Edge lists may repeat a pair, which creates parallel edges; see ismultigraph and simplify.

The edges are kept sorted, so G.Edges may list them in a different order from the input. You can read or add columns, for example G.Edges.Weight = [3; 4]. Use plot(G) to draw the graph and numnodes, numedges, neighbors and degree to inspect it.

Input arguments

s, t
End nodes of the edges: positive integers, or names given as cell arrays of text. Names create the nodes automatically.
w
Numeric weights, one per edge.
A
Square symmetric matrix. A(i,j) ~= 0 makes an edge between i and j.

Output arguments

G
A graph object. G.Edges is a table with the column EndNodes (and Weight if weights were given); G.Nodes is a table of node properties such as Name.

Example

Edge list, weights, matrix, names

G = graph([1 1 2], [2 3 3], [4 6 5]);
disp(G.Edges)
H = graph([0 1 1; 1 0 0; 1 0 0]);
disp(H.Edges.EndNodes)
N = graph({'a','b','c'}, {'b','c','a'});
disp(N.Nodes.Name')
Output
    EndNodes    Weight
    ________    ______

     1    2       4   
     1    3       6   
     2    3       5   
     1     2
     1     3
    {'a'}    {'b'}    {'c'}

See also

digraph addedge adjacency plot neighbors numnodes