MATLAB爱好者论坛-LabFans.com

MATLAB爱好者论坛-LabFans.com (https://www.labfans.com/bbs/index.php)
-   资料存档 (https://www.labfans.com/bbs/forumdisplay.php?f=72)
-   -   什么是函数句柄,它有什么用? (https://www.labfans.com/bbs/showthread.php?t=22655)

poster 2019-12-10 16:49

什么是函数句柄,它有什么用?
 
有人可以向我解释@ (函数句柄)运算符的含义以及为什么使用它吗?


回答:
MATLAB中的[URL="https://www.mathworks.com/help/matlab/matlab_prog/creating-a-function-handle.html"]函数句柄运算符[/URL]在本质上类似于指向函数特定实例的指针。其他一些答案已经讨论了它的一些用法,但是我将在这里添加它经常使用的另一种用法:维护对不再“在范围内”的函数的访问。

例如,以下函数初始化一个值count ,然后将函数句柄返回给嵌套的函数increment :

function fHandle = start_counting(count) disp(count); fHandle = @increment; function increment count = count+1; disp(count); end end 由于函数increment是[URL="https://www.mathworks.com/help/matlab/matlab_prog/nested-functions.html"]嵌套函数[/URL] ,因此只能在函数start_counting (即, start_counting的工作区是其“作用域”)。但是,通过返回函数increment的句柄,我仍然可以在start_counting之外使用它,并且它仍然保留对start_counting工作空间中变量的访问权!这使我可以这样做:

>> fh = start_counting(3); % Initialize count to 3 and return handle 3 >> fh(); % Invoke increment function using its handle 4 >> fh(); 5 请注意,即使我们不在函数start_counting我们如何也可以保持递增计数。但是,您可以通过使用另一个数字再次调用start_counting并将函数句柄存储在另一个变量中来做更有趣的事情:

>> fh2 = start_counting(-4); -4 >> fh2(); -3 >> fh2(); -2 >> fh(); % Invoke the first handle to increment 6 >> fh2(); % Invoke the second handle to increment -1 请注意,这两个不同的计数器是独立运行的。函数处理fh和fh2指向函数increment不同实例,这些实例具有不同的工作空间,这些工作空间包含count唯一值。

除上述内容外,将函数句柄与嵌套函数结合使用还可以帮助简化GUI设计,正如我在[URL="https://stackoverflow.com/a/425347/52738"]另一篇SO post中所[/URL]说明的那样。



[url=https://stackoverflow.com/questions/796935]更多&回答...[/url]


所有时间均为北京时间。现在的时间是 23:38

Powered by vBulletin
版权所有 ©2000 - 2025,Jelsoft Enterprises Ltd.