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)
% 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:
- distances - https://www.mathworks.com/help/matlab/ref/graph.distances.html
- subgraph - https://www.mathworks.com/help/matlab/ref/graph.subgraph.html#:~:text=The%20node%20numbering%20in%20the%20subgraph%20is%20reset
Hope this helps!