There are already a lot of answers to this question.
However, because I liked the question, and I love to procrastinate, here is my take at answering this (It is close to the approach presented by Dang Khoa, but different enough to be posted, in my opinion):
The idea is to run the profile
function, along with a digraph to represent the data.
profile on
Main % Code to be analized
p = profile('info');
Now p
is a structure. In particular, it contains the field FunctionTable
, which is a structure array, where each structure contains information about one of the calls during the execution of Main.m
. To keep only the functions, we will have to check, for each element in FunctionTable
, if it is a function, i.e. if p.FunctionTable(ii).Type
is 'M-function'
In order to represent the information, let's use a MATLAB's digraph object:
N = numel(p.FunctionTable);
G = digraph;
G = addnode(G,N);
nlabels = {};
for ii = 1:N
Children = p.FunctionTable(ii).Children;
if ~isempty(Children)
for jj = 1:numel(Children)
G = addedge(G,ii,Children(jj).Index);
end
end
end
Count = 1;
for ii=1:N
if ~strcmp(p.FunctionTable(ii).Type,'M-function') % Keep only the functions
G = rmnode(G,Count);
else
Nchars = min(length(p.FunctionTable(ii).FunctionName),10);
nlabels{Count} = p.FunctionTable(ii).FunctionName(1:Nchars);
Count = Count + 1;
end
end
plot(G,'NodeLabel',nlabels,'layout','layered')
G
is a directed graph, where node #i
refers to the i-th
element in the structure array p.FunctionTable
where an edge connects node #i
to node #j
if the function represented by node #i
is a parent to the one represented by node #j
.
The plot is pretty ugly when applied to my big program but it might be nicer for smaller functions:

Zooming in on a subpart of the graph:
