Automatically generating a diagram of function cal

2019-01-31 09:01发布

Anybody knows of a tool that can be used to automatically build diagrams of function calls in MATLAB?

E.g. For a given function, the tool would recursively go through function calls and build a 2D graph where nodes would represent functions and directed edges would connect calling functions with called functions.

Ideally the tool could allow the user to turn on and off filters to only include user-defined functions, limit the depth of recursion, etc.

I believe Doxygen provides some similar functionality for more traditional OOP languages, but I was wondering if something like this exists already for MATLAB.

Thanks!

1条回答
甜甜的少女心
2楼-- · 2019-01-31 09:40

You can use the techniques from those other answers referenced in gnovice's comment to get a list of function dependencies as (A,B) pairs, where A calls B. Then install GraphViz and use it to generate the diagrams. You can create the .dot files from Matlab with something like this.

function createFunctionDependencyDotFile(calls)
%CREATEFUNCTIONDEPENDENCYDOTFILE Create a GraphViz DOT diagram file from function call list
%
% Calls (cellstr) is an n-by-2 cell array in format {caller,callee;...}.
%
% Example:
% calls = { 'foo','X'; 'bar','Y'; 'foo','Z'; 'foo','bar'; 'bar','bar'};
% createFunctionDependencyDotFile(calls)

baseName = 'functionCalls';
dotFile = [baseName '.dot'];
fid = fopen(dotFile, 'w');
fprintf(fid, 'digraph G {\n');
for i = 1:size(calls,1)
    [parent,child] = calls{i,:};
    fprintf(fid, '   "%s" -> "%s"\n', parent, child);
end
fprintf(fid, '}\n');
fclose(fid);

% Render to image
imageFile = [baseName '.png'];
% Assumes the GraphViz bin dir is on the path; if not, use full path to dot.exe
cmd = sprintf('dot -Tpng -Gsize="2,2" "%s" -o"%s"', dotFile, imageFile);
system(cmd);
fprintf('Wrote to %s\n', imageFile);

enter image description here

GraphViz works great for lots of other tree and graph applications, like class inheritance and dependency trees, data flow, and so on.

查看更多
登录 后发表回答