Alex
Alex

Reputation: 15708

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

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

Upvotes: 2

Views: 396

Answers (1)

Luis Mendo
Luis Mendo

Reputation: 112679

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.

Upvotes: 2

Related Questions