为什么在不正确的上下文中使用此功能处理? [英] 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 presents一组重载函数),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]
我觉得我必须使用的函数句柄 @
在错误的上下文。任何人都可以告诉我吗? (备注,如在评论中所指出的显示答
很奇怪,因为 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).
推荐答案
在第一code片段,的意思是
是的 (命名)函数的和 @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){总和(X)/长度(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屋!