subgraph from graph matlab function

6 visualizaciones (últimos 30 días)
Hassan
Hassan el 29 de Oct. de 2012
Respondida: ag el 15 de Sept. de 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

Respuestas (1)

ag
ag el 15 de Sept. de 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!

Categorías

Más información sobre Graph and Network Algorithms en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by