Clear Filters
Clear Filters

Sorting names of nodes after graphtopoorder

4 views (last 30 days)
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!

Accepted Answer

Kristen Amaddio
Kristen Amaddio on 27 Jul 2017
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'

More Answers (1)

Moritz Geiger
Moritz Geiger on 29 Jul 2017
Thank you! It works! Fantastic!
I do not understand this line:
sortedNames = nNodes(order);
What is the background of this? Is the vector inside the brackets the attribute for sorting? I couldn't find it in the docu.
Thank you for your help!

Categories

Find more on Shifting and Sorting Matrices 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!