How to use MATLAB toolbox function which has the same name of a user defined function

后端 未结 2 883
天命终不由人
天命终不由人 2021-01-14 12:18

I am having a problem with the findpeaks function, this function is in the signal processing toolbox and also the program has another version of it (user define

相关标签:
2条回答
  • 2021-01-14 12:39

    The precedence order used by MATLAB is described in their help pages. It states that functions in the current folder (9.) are preferred over functions elsewhere in the path (10.). Then, the first appearance of the function in the path is chosen. This allows for a number of possible solutions:

    1. cd to folder

    A very simple method is simply to change the current workspace directory to the folder of the function you need to call, i.e. cd either to the place where your user-defined function is, or cd to the toolbox path. Note: This is rather inelegant, but probably sometimes the simplest solution.

    2. Reorder path

    As mentioned, MATLAB choses the first occurence of the function in the path. You can thus re-sort the path variable, so the folder where your user-defined function is, appears last. The path variable can be viewed and manipulated using the path function. Note: Then you can only call the toolbox function. Otherwise you'd have to resort the path again.

    3. Function handles

    If you need to be able to call both functions, it can be useful to create a function handle for both versions. For that, you have to cd into the folders where the functions are defined and create a new handle there:

    cd('path/to/userdefined/function')
    userFindPeaks = @findpeaks;
    cd('path/to/MATLAB/installation/toolbox/signal/signal')
    toolboxFindPeaks = @findpeaks;
    

    You can then call the functions using feval.

    Of course, as Adriaan mentions in the comments, it is best not to use the names of already defined functions for your own functions or for variable names.

    0 讨论(0)
  • 2021-01-14 13:02

    I just came here looking for the same thing... I ended up using builtin. https://uk.mathworks.com/help/matlab/ref/builtin.html

    [y1,...,yn] = builtin(function,x1,...,xn)
    

    @arr_sea actually posted a link in one of the folded comments which uses this function in a different context.

    0 讨论(0)
提交回复
热议问题