为什么在不正确的上下文中使用此函数句柄? [英] Why is this function handle being used in the incorrect context?
问题描述
我想了解如何将函数传递给 varfun
,我想这适用于 arrayfun
、cellfun
等.
I am trying to understand how to pass functions to varfun
, which I suppose applies to arrayfun
, cellfun
etc.
阅读帮助文件,第一个参数应该是:
Reading the helpfile, the first argument should be:
函数,指定为函数句柄.您可以在文件中定义该函数,也可以将其定义为匿名函数.如果 func 对应多个函数文件(即如果 func 表示一组重载函数),MATLAB 会根据输入参数的类别确定调用哪个函数.
Function, specified as a function handle. You can define the function in a file or as an anonymous function. If func corresponds to more than one function file (that is, if func represents a set of overloaded functions), MATLAB determines which function to call based on the class of the input arguments.
所以我尝试使用以下数据:
So I try it with the following data:
sampleId = [1 1 1 3 3 3]';
entity = [1 2 3 1 4 5]';
dataTable = table(sampleId, entity)
是的:
varfun(@mean, dataTable)
ans =
mean_sampleId mean_entity
_____________ ___________
2 2.6667
现在,我匿名定义自己的函数时出现问题,例如:
Now, my problem occurs when I define my own function anonymously, for example:
mymean = @(x){sum(x)/length(x)};
然后抛出一个错误:
varfun(@mymean, dataTable)
Error: "mymean" was previously used as a variable, conflicting with its use here as the name of a function or command.
See "How MATLAB Recognizes Command Syntax" in the MATLAB documentation for details.
然而,如果我不使用 at 符号,我会得到:
Yet, if I do not use the at symbol, I get:
varfun(mymean, dataTable)
ans =
Fun_sampleId Fun_entity
____________ __________
[2] [2.6667]
我觉得我一定是在错误的上下文中使用了函数句柄 @
.任何人都可以启发我吗?(请注意,如注释中所述,ans
的显示很奇怪,因为 mymean
返回一个元胞数组.这是一个无意的错误.
I feel like I must be using the function handle @
in the wrong context. Can anyone enlighten me? (Remark, as noted in the comments the display of ans
is strange because mymean
returns a cell array. This was an unintentional error).
推荐答案
在第一个代码片段中,mean
是一个 (命名)函数,而 @mean
是一个 函数句柄到该函数.你可以等效地使用
In the first code snippet, mean
is a (named) function, and @mean
is a function handle to that function. You could equivalently use
f = @mean;
varfun(f, dataTable)
在第二种情况下,当你定义
In the second case, when you define
mymean = @(x){sum(x)/length(x)};
@(x){sum(x)/length(x)}
部分是 匿名函数,变量 mymean
又是一个 函数句柄那个(匿名)函数.所以你需要使用 varfun(mymean, dataTable)
,而不是 varfun(@mymean, dataTable)
.
the @(x){sum(x)/length(x)}
part is an anonymous function, and the variable mymean
is again a function handle to that (anonymous) function. So you need to use varfun(mymean, dataTable)
, not varfun(@mymean, dataTable)
.
因此,正在使用 @
符号 以两种不同的方式,尽管在这两种情况下它都会产生一个函数句柄:
So, the @
sign is being used in two different ways, although in both cases it produces a function handle:
- 案例 1:从命名函数创建函数句柄.命名函数是在其自己的文件中定义的函数.
- 案例 2:作为匿名函数定义的一部分.匿名函数是直接定义的,而不是在单独的文件中.该定义构造了一个匿名函数并自动返回该函数的句柄.
这篇关于为什么在不正确的上下文中使用此函数句柄?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!