检查我的函数是否覆盖了另一个函数

时间:2014-09-23 18:56:23

标签: matlab

我试图在运行时找出我的函数是否覆盖了另一个函数。

考虑以下假设情景。我正在实现一个名为freqz的函数,如果安装了Signal Processing Toolbox,它可能存在于MATLAB中。如果确实已经作为工具箱的一部分存在,我想在我自己的内部调用它并返回其结果。如果它不存在,我希望自己的功能可以自己处理。

这是一个样本伪代码

function foo(args)
    if overrides_another_function(foo)
        func = find_overriden_function(foo);
        result = func(args);
    else
        result = my_own_processing(args);

    return result;

在这种情况下,当有人拨打foo时,他们会获得他们期望的版本,如果foo从其他地方无法使用,则会依赖我自己的实施。 MATLAB能够做这样的事吗?

我尝试了什么:

  • exist内调用foo始终返回2(函数存在),因为一旦我们第一次进入函数,就会认为函数被声明了。
  • 从m文件中的函数外部运行exist是无效的MATLAB语法。
  • 我还没有找到一种方法来列出具有给定名称的所有函数。如果可以实现,那将会让我走到一半(我至少知道存在,但仍然需要弄清楚如何访问被覆盖的函数)。

3 个答案:

答案 0 :(得分:2)

通过调用which,您可以获得任何功能的完整路径。假设您没有在名为toolbox的文件夹中放置任何自定义函数,这似乎工作得很好:

x = which('abs', '-all'); %// Returns a cell array with all the full path 
                          %// functions called abs in order of precedence

现在,检查是否有任何已安装的工具箱中的任何一个:

in_toolbox = any(cellfun(@(c) any(findstr('toolbox',c)), x));

如果函数'abs'已经存在于您的某个工具箱中,则返回true,如果函数不存在,则返回0。从那里我认为应该可以避免使用你自己定制的。

您还可以在'built-in'中查看findstr,但我发现工具箱中的某些功能并未在名称前面显示。

答案 1 :(得分:0)

只有两个建议,而不是真正的答案。

也许通过按名称查找脚本(foo)http://www.mathworks.nl/help/matlab/ref/which.html 但这也可能指向你已经存在的foo。

否则,您必须搜索foo出现的完整路径。

答案 2 :(得分:0)

功能代码

function result = feval1(function_name,args)

%// Get the function filename by appending the extension - '.m'
relative_filename = strcat(function_name,'.m');

%// Get all possible paths to such a function with .m extension
pospaths = strcat(strsplit(path,';'),filesep,relative_filename);

%// All paths that have such function file(s)
existing_paths = pospaths(cellfun(@(x) exist(x,'file'),pospaths)>0);

%// Find logical indices for toolbox paths(if this function is a built-in one)
istoolbox_path = cellfun(@(x) strncmp(x,matlabroot,numel(matlabroot)),existing_paths);

%// Find the first toolbox and nontoolbox paths that have such a function file
first_toolbox_path = existing_paths(find(istoolbox_path,1,'first'));
first_nontoolbox_path = existing_paths(find(~istoolbox_path,1,'first'));

%// After deciding whether to use a toolbox function with the same function name 
%// (if available) or the one in the current directory, create a function handle 
%// based on the absolute path to the location of the function file
if ~isempty(first_toolbox_path)
    func = function_handle(first_toolbox_path);
    result = feval(func,args);
else
    func = function_handle(first_nontoolbox_path);
    result = feval(func,args);
end

return;

请注意,上述功能代码使用可从here获取的名为function handle的FEX代码。

样本用法 -

function_name = 'freqz';             %// sample function name
args = fircls1(54,0.3,0.02,0.008);   %// sample input arguments to the sample function
result = feval1(function_name,args)  %// output from function operation on input args
相关问题