Why is this function handle being used in the incorrect context?

陌路散爱 提交于 2019-12-30 11:05:15

问题


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:

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)

And yes:

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)};

Then an error is thrown:

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.

Yet, if I do not use the at symbol, I get:

varfun(mymean, dataTable)

ans = 

    Fun_sampleId    Fun_entity
    ____________    __________

    [2]             [2.6667]  

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).


回答1:


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)};

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:

  • Case 1: to create a function handle from a named function. A named function is a function that is defined in its own file.
  • Case 2: as part of an anonymous function definition. An anonymous function is defined directly, not in a separate file. The definition constructs an anonymous function and automatically returns a handle to that function.


来源:https://stackoverflow.com/questions/32130039/why-is-this-function-handle-being-used-in-the-incorrect-context

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!