MATLAB: Sorting names of nodes after graphtopoorder

graphtopoorder sort

Hello community! I'm quite successful with my Matlab skills I earnes within the last four days. After using graphtopoorder I'm missing the sorting of the Node-Names too. First I make a sparse from my adjaceny, then using the topo order.
order = graphtopoorder(S)
My node names are "nNodes".
How is it possible to sort the names in the order of the topo order? fgh=sort(nNames,j) didn't work…
Thank you!

Best Answer

You can use array indexing in order to sort the 'nNodes' in terms of the topological order generated by 'graphtopoorder'. I set up a simple example to reproduce your workflow:
% Simple DAG example
s = [1 1 1 2 2 3];
t = [2 3 4 5 6 7];
G = digraph(s,t);
% Define nNodes
nNodes = {'First' 'Second' 'Third' 'Fourth' 'Fifth' 'Sixth' 'Seventh'}';
G.Nodes.Name = nNodes;
% Create the adjacency matrix based on the DAG
% Then use this to create a sparse matrix
A = adjacency(G);
S = sparse(A);
% Get the topological sort of the DAG
order = graphtopoorder(S);
% Use indexing to sort the node names in terms of the topological order
sortedNames = nNodes(order);
Here you will see that the 'sortedNames' correspond to the sorted node order specified by 'order':
order =
1 4 3 7 2 6 5
sortedNames =
7×1 cell array
'First'
'Fourth'
'Third'
'Seventh'
'Second'
'Sixth'
'Fifth'