Labfans是一个针对大学生、工程师和科研工作者的技术社区。 | 论坛首页 | 联系我们(Contact Us) |
![]() |
![]() |
#1 |
高级会员
注册日期: 2019-11-21
帖子: 3,006
声望力: 66 ![]() |
![]()
有人可以向我解释@ (函数句柄)运算符的含义以及为什么使用它吗?
回答: MATLAB中的函数句柄运算符在本质上类似于指向函数特定实例的指针。其他一些答案已经讨论了它的一些用法,但是我将在这里添加它经常使用的另一种用法:维护对不再“在范围内”的函数的访问。 例如,以下函数初始化一个值count ,然后将函数句柄返回给嵌套的函数increment : function fHandle = start_counting(count) disp(count); fHandle = @increment; function increment count = count+1; disp(count); end end 由于函数increment是嵌套函数 ,因此只能在函数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设计,正如我在另一篇SO post中所说明的那样。 更多&回答... |
![]() |
![]() |