Create a function handle to a local function from outside of the function
5 次查看(过去 30 天)
显示 更早的评论
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!
0 个评论
回答(1 个)
Vinayak Choyyan
2022-12-12
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
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Testing Frameworks 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!