Main Content

subgraph

Extract subgraph

Description

example

H= subgraph(G,nodeIDs)返回的子图Gthat contains only the nodes specified bynodeIDs.

H= subgraph(G,idx)specifies the subgraph nodes using a logical vector.

Examples

collapse all

Create and plot a graph.

s = [1 1 1 1 2 2 2 2 2 2 2 2 2 2 15 15 15 15 15]; t = [3 5 4 2 14 6 11 12 13 10 7 9 8 15 16 17 19 18 20]; G = graph(s,t); plot(G,'Layout','force')

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

Extract a subgraph fromGby specifying which nodes to include. The node numbering in the subgraph is reset.

idx = [2 15 16 17 18 19 20 1 3 4 5]; H = subgraph(G,idx); plot(H,'Layout','force')

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

Create and plot a weighted graph with named nodes.

s = [1 1 1 2 2 2 8 8 8 8]; t = [2 3 4 5 6 7 9 10 11 12]; weights = [10 30 40 80 60 60 20 30 90 80]; names = {'A''B''C''D''E''F''G''H''I''J''K''L'}; G = graph(s,t,weights,names); plot(G,'EdgeLabel',G.Edges.Weight)

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

Extract a subgraph that contains node'B'and all of its neighbors.subgraphpreserves the node names and edge weights. However, the numeric node IDs inHare renumbered compared toG.

N = neighbors(G,'B'); H = subgraph(G, ['B'; N]); plot(H,'EdgeLabel',H.Edges.Weight)

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

Input Arguments

collapse all

输入graph, specified as either agraphordigraphobject. Usegraphto create an undirected graph ordigraphto create a directed graph.

Example:G = graph(1,2)

Example:G = digraph([1 2],[2 3])

Node identifiers, specified as one or more node indices or node names.nodeIDsselects a subset of the nodes inGto generate the subgraph,H.

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

Form Single Node Multiple 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"]

Example:H = subgraph(G,[1 2 5])

Example:H = subgraph(G,{'A' 'B' 'E'})

Node selection vector, specified as a logical vector. The subgraph contains only the nodesJfor whichidx(J)is logical1(true). The index of nodeJinHisI(J), whereI = find(idx).

Example:subgraph(G,degree(G)>2)

Data Types:logical

Output Arguments

collapse all

Subgraph, returned as agraphordigraphobject.Hcontains only the nodes that were selected withnodeIDsoridx. Other nodes inG(and the edges connecting to those nodes) are discarded. The node properties and edge properties of the selected nodes and edges are carried over fromGintoH.

Seegraphordigraphfor more information about graph objects.

Extended Capabilities

Version History

Introduced in R2015b