什么是函数句柄,它如何有用? [英] What is a function handle and how is it useful?
问题描述
有人可以向我解释 @
(函数句柄)运算符的含义,以及为什么要使用它?
The MATLAB中的函数句柄运算符的作用基本上就像指向特定函数实例的指针。其他一些答案已经讨论了它的一些用途,但是我会在这里添加另一个我经常用到的用法:保持对不在范围内的函数的访问。
例如,下面的函数初始化一个值 count
,然后返回一个嵌套函数 increment
$ b $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $'
fHandle = @increment;
函数增量
count = count + 1;
disp(count);
end
end
由于函数 increment
是一个嵌套函数 a>,它只能在 start_counting
函数中使用(即 start_counting
的工作空间是它的范围) 。但是,通过返回函数 increment
的句柄,我仍然可以在 start_counting
之外使用它,它仍然保留访问 start_counting
工作区中的变量!这允许我这样做:
>> fh = start_counting(3); %初始化计数为3并返回句柄
3
>> FH(); %使用其句柄调用增量函数
4
>> FH();
5
请注意,即使我们不在函数 start_counting
。但是,通过再次调用 start_counting
并使用另一个数字并将函数句柄存储在另一个变量中,您可以做更有趣的事情:
>> fh2 = start_counting(-4);
-4
>> FH2();
-3
>> FH2();
-2
>> FH(); %调用第一个句柄以增加
6
>> FH2(); %调用第二个句柄以增加
-1
请注意,这两个不同的计数器独立运行。函数处理 fh
和 fh2
指向函数 increment $ c的不同实例$ c>,其中包含
count
的唯一值的不同工作空间。除了上述内容,还可以使用函数句柄与嵌套函数的结合也可以帮助简化GUI设计,正如我在这篇其他SO贴子中所说明的那样。
Can somebody explain to me the meaning of the @
(function handle) operator and why to use it?
The function handle operator in MATLAB acts essentially like a pointer to a specific instance of a function. Some of the other answers have discussed a few of its uses, but I'll add another use here that I often have for it: maintaining access to functions that are no longer "in scope".
For example, the following function initializes a value count
, and then returns a function handle to a nested function increment
:
function fHandle = start_counting(count)
disp(count);
fHandle = @increment;
function increment
count = count+1;
disp(count);
end
end
Since the function increment
is a nested function, it can only be used within the function start_counting
(i.e. the workspace of start_counting
is its "scope"). However, by returning a handle to the function increment
, I can still use it outside of start_counting
, and it still retains access to the variables in the workspace of start_counting
! That allows me to do this:
>> fh = start_counting(3); % Initialize count to 3 and return handle
3
>> fh(); % Invoke increment function using its handle
4
>> fh();
5
Notice how we can keep incrementing count even though we are outside of the function start_counting
. But you can do something even more interesting by calling start_counting
again with a different number and storing the function handle in another variable:
>> 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
Notice that these two different counters operate independently. The function handles fh
and fh2
point to different instances of the function increment
with different workspaces containing unique values for count
.
In addition to the above, using function handles in conjunction with nested functions can also help streamline GUI design, as I illustrate in this other SO post.
这篇关于什么是函数句柄,它如何有用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!