subgraph from graph matlab function

6 次查看(过去 30 天)
Hassan
Hassan 2012-10-29
回答: ag 2024-9-15
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

回答(1 个)

ag
ag 2024-9-15
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!

类别

Help CenterFile Exchange 中查找有关 Graph and Network Algorithms 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by