Search code examples
matlabunit-testingpackagefunction-handle

`localfunctions` inside a package


localfunctions returns function handles to all the local functions in an m-file. However, this doesn't work in a package. For example, the following code saved as 'a.m' runs fine:

function fs = a()
    fs = localfunctions;
end

function babo()
end

function hidden()
end

Called from MATLAB console:

>> a()

ans = 

    @babo  
    @hidden

But when it is inside a package as '+aaa/b.m', I get nothing:

>> aaa.b()

ans = 

     {}

I don't think this behavior is well documented. How do I overcome this? I need to use localfunctions to unit test some functions within the package and I don't want to keep it outside of the package just because of this.


Solution

  • One solution would be to import the package before calling localfunctions:

    +mypkg/mytest.m

    function f = mytest()
        import mypkg.*
        f = localfunctions;
    end
    
    function foo()
    end
    
    function bar()
    end
    

    When called:

    >> f = mypkg.mytest()
    f = 
        @foo
        @bar
    
    >> functions(f{1})
    ans = 
         function: 'foo'
             type: 'scopedfunction'
             file: 'C:\Users\Amro\Desktop\+mypkg\mytest.m'
        parentage: {'foo'  'mytest'}