subgraph from graph matlab function

6 views (last 30 days)
Hassan
Hassan on 29 Oct 2012
Answered: ag on 15 Sep 2024
if i have a graph such as
WW = [20 10 12 14 12 10 20];
from=[1 2 2 3 4 3 5];
to = [4 1 4 2 3 5 4];
DG = sparse(from,to,WW); UG = tril(DG + DG');
d=graphallshortestpaths(UG,'directed',false);
is there any method to take subgraph for example(graph that contain only nodes 1 3 5)
thanks in advance
hassan

Answers (1)

ag
ag on 15 Sep 2024
Hi Hassan,
To extract a subgraph containing only specific nodes from an undirected graph, you can use the "subgraph" function in MATLAB. However, since "distance" ("graphallshortestpaths" is deprecated) returns a distance matrix rather than a graph object, you will need to first create a graph object from the adjacency matrix.
The below code snippets illustrates how to achieve this:
WW = [20 10 12 14 12 10 20];
from = [1 2 2 3 4 3 5];
to = [4 1 4 2 3 5 4];
% Create a sparse adjacency matrix for the directed graph
DG = sparse(from, to, WW)
DG = 5x5 sparse double matrix (7 nonzeros)
(2,1) 10 (3,2) 14 (4,3) 12 (1,4) 20 (2,4) 12 (5,4) 20 (3,5) 10
% Convert the directed graph to an undirected graph
UG = DG + DG';
% Create a graph object from the undirected adjacency matrix
G = graph(UG);
% Compute all-pairs shortest paths (distance matrix)
d = distances(G);
% Specify the nodes for the subgraph
selectedNodes = [1, 3, 5];
% Create the subgraph containing only the specified nodes
subG = subgraph(G, selectedNodes);
% Display the subgraph
plot(subG, 'EdgeLabel', subG.Edges.Weight);
Please note, that the node numbering in the subgraph is reset.
For more details, please refer to the following MathWorks documentations:
Hope this helps!

Categories

Find more on Graph and Network Algorithms in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!