2014-09-23 75 views
5

我想在运行时找出我的函数是否覆盖另一个函数。检查我的函数是否覆盖另一个函数

考虑以下假设情况。如果安装了信号处理工具箱,我正在执行一个名为freqz的函数,它可能存在于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能做这样的事吗?

我已经试过:

  • 调用内fooexist总是返回2(函数存在),因为一个功能被认为声明一次我们里面的第一次。
  • 从外部运行exist函数在m文件中是无效的MATLAB语法。
  • 我还没有找到一种方法来列出给定名称的所有功能。如果有可能实现,那会让我有一半的存在(我至少知道存在,但仍然需要弄清楚如何访问重写的函数)。
+0

您可以创建在你的工作空间中的子文件夹包含“您”的功能。起初他们应该对你的主函数不知道,所以你可以检查原函数的存在('which'等) - 如果结果为空,你可以使用'addpath'来添加你的自定义函数的文件夹。使用面向对象的编程可能有更优雅的方法。但我并不熟悉这一点。 – thewaywewalk 2014-09-23 19:16:42

+0

这里提供的解决方案是否适合您? – Divakar 2014-09-29 09:14:39

回答

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。从那里我认为应该可以避免使用自己定制的。

您也可以在findstr中检查'built-in',但是我发现工具箱中的某些功能没有在名称前面有这个功能。

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; 

请注意上面的功能代码使用名为function handle一个FEX的代码,可以从here获得。

使用范例 -

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