Clear Filters
Clear Filters

Create a function handle to a local function from outside of the function

3 views (last 30 days)
Hi,
Is there any way to create a handle to a local function from a function outside of the current m-file?
Specifically, this is my example func.m:
function lfhs = func()
lfhs = localfunctions;
end
function tests()
func();
end
From this I can extract handle to tests(), if I run
>> func_tests = func()
func_tests =
1×1 cell array
{@tests}
but I need to explicitly add call to localfunctions in the function itself, and on top reserve an output for that purpose.
I'd like to be able to create a handle to tests() without adding anything new (i.e., call to localfunctions) to function func(). Is that possible? Obviously str2func('func>tests') or any similar syntax doesn't work.
Alternatively, is there a way to convert the structure returned by functions() back into a working function handle? E.g.,:
>> functions(func_tests{1})
ans =
struct with fields:
function: 'tests'
type: 'scopedfunction'
file: 'C:\...\func.m'
parentage: {'tests' 'func'}
>> ????(ans)
ans =
function_handle with value:
@tests
One of the reasons I want to do that would be integartion of unit tests as local functions inside of each individual function, e.g.,:
for fn=["func","etc"]
ftest = createHandleToTest(fn);
ftest(); %Run tests
end
Thanks!

Answers (1)

Vinayak Choyyan
Vinayak Choyyan on 12 Dec 2022
Hi Robert
As per my understanding, you would like to get function handles outside a m file.
I believe it is not possible to directly get local function handles outside a m file. One way to do this would be to have the functions inside a class. Here is an example
test1.m file
classdef test1
methods (Static)
function func1(obj)
a=5;
a
end
end
end
>> obj=test1;
>> k=@obj.func1;
>> k()
a =
5

Categories

Find more on Testing Frameworks in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!