Search code examples
matlabfunction-handle

MATLAB: Function Handle of Nested Function


Is there a way to create a function handle to a nested function that includes the parent function in the function handle?

As an example, say I have:

function myP = myParent()

    myP.My_Method = myMethod;

    function myMethod()
        disp "hello world"
    end
end

In another file, I could call the method by doing something like:

myP = myParent();
myP.My_Method();

But, if I have another function that takes function handles as a parameter and then calls the function, how do I pass in the function handle to myMethod in this case, since this new function can't create a myParent variable.


Solution

  • The following seems to work:

    function myP = myParent()
    
        myP.My_Method = @myMethod;
    
        function myMethod()
            s=dbstack;
            fprintf('Hello from %s!\n',s(1).name);
        end
    end
    

    Running it as follows:

    >> myP = myParent()
    myP = 
        My_Method: @myParent/myMethod
    >> feval(myP.My_Method)
    Hello from myParent/myMethod!
    >> myP.My_Method()
    Hello from myParent/myMethod!
    

    It is also fine to run it from another function:

    % newfun.m
    function newfun(hfun)
    feval(hfun)
    

    Test:

    >> newfun(myP.My_Method)
    Hello from myParent/myMethod!
    

    Depending on what you are doing, this should be enough. Note that each handle you create is unique since it contains information about externally scoped variables (variables pulled in the parent):

    When you create a function handle for a nested function, that handle stores not only the name of the function, but also the values of externally scoped variables.