有没有办法为嵌套函数创建函数句柄,并将父函数包含在函数句柄中?
举个例子,假设我有:
function myP = myParent()
myP.My_Method = myMethod;
function myMethod()
disp "hello world"
end
end
在另一个文件中,我可以通过执行以下操作来调用该方法:
myP = myParent();
myP.My_Method();
但是,如果我有另一个函数将函数句柄作为参数然后调用该函数,那么在这种情况下我如何将函数句柄传递给 myMethod
,因为这个新函数可以'创建一个 myParent
变量。
最佳答案
以下似乎有效:
function myP = myParent()
myP.My_Method = @myMethod;
function myMethod()
s=dbstack;
fprintf('Hello from %s!\n',s(1).name);
end
end
运行如下:
>> myP = myParent()
myP =
My_Method: @myParent/myMethod
>> feval(myP.My_Method)
Hello from myParent/myMethod!
>> myP.My_Method()
Hello from myParent/myMethod!
从另一个函数运行它也可以:
% newfun.m
function newfun(hfun)
feval(hfun)
测试:
>> newfun(myP.My_Method)
Hello from myParent/myMethod!
根据您在做什么,这应该足够了。请注意,您创建的每个句柄都是唯一的,因为 it contains information about externally scoped variables (在父级中拉入的变量):
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.
关于MATLAB:嵌套函数的函数句柄,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21299446/