Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if my function overrides another function

Tags:

matlab

I'm trying to find out at runtime whether my function overrides another function.

Consider the following hypothetical scenario. I'm implementing a functional called freqz which may exist in MATLAB if the Signal Processing Toolbox is installed. If it does indeed already exist as a part of the toolbox, I want to call it inside my own and return its result. If it does not exist, I would like my own function to do its own processing.

Here's a sample pseudocode

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

    return result;

In this case, when someone calls foo, they'll get the version they expect, and fall back on my own implementation if foo is unavailable from elsewhere. Is MATLAB capable of doing something like this?

What I've tried:

  • Calling exist within foo always returns 2 (function exists) because a function is considered declared once we're inside it for the first time.
  • Running exist from outside a function in an m-file is invalid MATLAB syntax.
  • I haven't found a way to list all functions with a given name. If that's possible to achieve, that would get me half way there (I would at least know about existence, but would still need to figure out how to access the overridden function).
like image 211
Phonon Avatar asked Nov 01 '22 16:11

Phonon


1 Answers

By calling which you can get the full path of any function. Assuming you don't put any custom functions inside folders named toolbox, this seems to work quite well:

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

Now, to check if any of these are in any of your installed toolboxes:

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

This will return true if the function 'abs' already exist in one of your toolboxes, and 0 if it doesn't. From there I think it should be possible to avoid using your own custom made one.

You can also check for 'built-in' in the findstr, but I find that some functions from toolboxes doesn't have this in front of the name.

like image 169
Stewie Griffin Avatar answered Nov 08 '22 04:11

Stewie Griffin