2

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.

Amro
  • 123,847
  • 25
  • 243
  • 454
Memming
  • 1,731
  • 13
  • 25
  • Clarifying question: Are you trying to expose the local functions of a package function in order to explicitly test those local functions themselves, or are you trying to write the test itselt as a function residing in a package using this api:http://www.mathworks.com/help/matlab/matlab_prog/write-function-based-unit-tests-.html – Andy Campbell Aug 28 '14 at 13:17

2 Answers2

3

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'}
Amro
  • 123,847
  • 25
  • 243
  • 454
  • unfortunately this is less than ideal because you have to hard-code the package name inside the function (related: http://stackoverflow.com/q/5637015/97160, http://stackoverflow.com/q/5635413/97160) – Amro Aug 27 '14 at 16:39
2

There is a bug in R2013b and R2014a where localfunctions does not respect the package of the file containing the local functions. This bug has been reported to The MathWorks for fixing in a future release.

Until then, Amro's workaround is the best option.

EDIT: This has been fixed in release R2014b.

Andy Campbell
  • 2,177
  • 13
  • 15