How to wrap an already existing function with a new function of the same name

后端 未结 3 964
忘掉有多难
忘掉有多难 2020-12-06 13:37

Is it possible to create a wrapper around a function that has the exact same name as the original function?

This would be very useful in circumstances where the user

3条回答
  •  南方客
    南方客 (楼主)
    2020-12-06 13:59

    I prefer jmetz's approach using builtin() when it can be applied, because it is clean and to the point. Unfortunately, many many functions are not found by builtin().

    I found that I was able to wrap a function using a combination of the which -all and cd commands. I suspect that this approach can be adapted to a wide variety of applications.

    In my example case, I wanted to (temporarily) wrap the interp1 function so that I could check for NaN output values. (The interp1 function will, by default, return a NaN under some conditions, such as if a query point is larger than the largest sample point.) Here's what I came up with:

    function Vq = interp1(varargin)
    
       persistent interp1_builtin;
    
       if (isempty(interp1_builtin)) % first call: handle not set
          toolbox = 'polyfun';
    
          % get a list of all known instances of the function, and then 
          % select the first such instance that contains the toolbox name
          % in its path
    
          which_list = which('interp1','-all');
          for ii = 1:length(which_list)
             if (strfind(which_list{ii}, [filesep, toolbox, filesep]))
                base_path = fileparts(which_list{ii}); % path to the original function
                current_path = pwd;
                cd(base_path); % go to the original function's directory
                interp1_builtin = @interp1; % create a function handle to the original function
                cd(current_path); % go back to the working directory
                break
             end
          end
       end
    
       Vq = interp1_builtin(varargin{:});  % call the original function
    
       % test if the output was NaN, and print a message
       if (any(isnan(Vq)))
          dbstack;
          disp('ERROR: interp1 returned a NaN');
          keyboard
       end
    
    end
    

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

提交回复
热议问题