这不是完全自动的,并且使用半记录函数getcalliinfo,但也许它可能会有所帮助。
来自help getcallinfo:
GETCALLINFO Returns called functions and their first and last lines
This function is unsupported and might change or be removed without
notice in a future version.
考虑这个示例函数,它使用多个工具箱并包含一个本地函数:
function y = example(x)
a = sinc(2);
b = example_local_function(pi);
c = @xcorr;
d = c([1 2 3], [4 5 6]);
y = imdilate(x,[1 1; 1 1]);
end
function z = example_local_fun(t)
z = t.^2 + exprnd(1);
end
将此函数保存到文件example.m 并运行getcallinfo 给出
>> getcallinfo('example.m')
Name Type Starts Ends Length Full Name
---- ---- ------ ---- ------ ---------
example function 1 7 7 example
example_local_fun subfunction 9 11 3 example>example_local_fun
ans =
1×2 struct array with fields:
type
name
fullname
functionPrefix
calls
firstline
lastline
linemask
结果是一个包含两个条目的结构数组:第一个用于主函数,第二个用于本地函数。观察第一个条目:
>> t(1)
ans =
struct with fields:
type: [1×1 internal.matlab.codetools.reports.matlabType.Function]
name: 'example'
fullname: 'example'
functionPrefix: 'example>'
calls: [1×1 struct]
firstline: 1
lastline: 7
linemask: [11×1 logical]
被调用的函数在
>> t(1).calls
ans =
struct with fields:
fcnCalls: [1×1 struct]
innerCalls: [1×1 struct]
dotCalls: [1×1 struct]
atCalls: [1×1 struct]
具体来说,在这种情况下,只有两个非空结构是
>> t(1).calls.fcnCalls
ans =
struct with fields:
names: {'sinc' 'example_local_function' 'pi' 'imdilate'}
lines: [2 3 3 6]
>> t(1).calls.atCalls
ans =
struct with fields:
names: {'xcorr'}
lines: 4
要查看被调用函数的定义位置,您可以将which 应用于字段names 中包含的元胞数组中的每个元胞:
C:\Program Files\MATLAB\R2018b\toolbox\signal\signal\sinc.m
'example_local_function' not found.
built-in (C:\Program Files\MATLAB\R2018b\toolbox\matlab\elmat\pi)
C:\Program Files\MATLAB\R2018b\toolbox\images\images\imdilate.m
要使过程自动化,您需要知道工具箱文件夹的名称(这很容易从您的 Matlab 安装中看出)。例如,图像处理工具箱是'images'(或者您可能更喜欢使用完整路径以避免误报):
>> s = cellfun(@which, t(1).calls.fcnCalls.names, 'UniformOutput', false);
>> ind = ~cellfun(@isempty, regexp(s, 'images', 'once'));
>> t(1).calls.fcnCalls.names(ind)
>> t(1).calls.fcnCalls.names(ind)
ans =
1×1 cell array
{'imdilate'}
其他工具箱的过程相同。比如Signal Processing Toolbox的文件夹叫'signals':
>> s = cellfun(@which, t(1).calls.fcnCalls.names, 'UniformOutput', false);
>> ind = ~cellfun(@isempty, regexp(s, 'signal', 'once'));
>> t(1).calls.fcnCalls.names(ind)
ans =
1×1 cell array
{'sinc'}
同样,对于其他类型的调用:
>> s = cellfun(@which, t(1).calls.atCalls.names, 'UniformOutput', false);
>> ind = ~cellfun(@isempty, regexp(s, 'signal', 'once'));
>> t(1).calls.atCalls.names(ind)
ans =
1×1 cell array
{'xcorr'}
或者对于局部函数:
>> s = cellfun(@which, t(2).calls.fcnCalls.names, 'UniformOutput', false)
>> ind = ~cellfun(@isempty, regexp(s, 'stats', 'once'));
>> t(2).calls.fcnCalls.names(ind)
ans =
1×1 cell array
{'exprnd'}