What happens within this code?

Hey guys, Im pretty new to Matlab programming but I do have some experience in C.
To understand Matlab I would like to understand the following code step by step. The code is a Topsort-algorithm to determine a topological order of edges of a digraph. It turned out that I do understand it better when every line is commented step by step explaining what is happening. Unfortunately I dont get it yet because of no experience.
So, I would really appreciate if you could help me by commenting every line and say what is happening in this line. THANK YOU very much in advance!
Malcom
1)
function order = topsort(A)
%
% order = topsort(A), where A is an adjacency matrix of a DAG.
% Return the nodes in topological order (parents before children).
if 0
% This method breaks if the graph isn't 1 connected component
start = 1;
directed = 1;
[d, pre, post, height, cycle] = dfs(A, start, directed);
assert(~cycle);
order = reverse(post);
end
n = length(A);
indeg = zeros(1,n);
zero_indeg = []; % a queue of nodes with no parents
for i=1:n
indeg(i) = length(parents(A,i));
if indeg(i)==0
zero_indeg = [i zero_indeg];
end
end
t=1;
order = zeros(1,n);
while ~isempty(zero_indeg)
v = zero_indeg(1);
zero_indeg = zero_indeg(2:end);
order(t) = v;
t = t + 1;
cs = children(A, v);
for j=1:length(cs)
c = cs(j);
indeg(c) = indeg(c) - 1;
if indeg(c) == 0
zero_indeg = [c zero_indeg];
end
end
end[/i]
2)
function ps = parents(adj_mat, i)
%
% ps = parents(adj_mat, i)
% Return the list of parents of node i
ps = find(adj_mat(:,i))';
3)
function ps = children(adj_mat, i)
%
% c = children(adj_mat, i)
% Return the list of children of node i
ps = find(adj_mat(i,:));

Answers (0)

Categories

Find more on Graph and Network Algorithms in Help Center and File Exchange

Asked:

on 10 May 2012

Community Treasure Hunt

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

Start Hunting!