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

前端 未结 1 2035
说谎
说谎 2021-01-15 05:11

I am trying to understand how to pass functions to varfun, which I suppose applies to arrayfun, cellfun etc.

Reading the helpf

相关标签:
1条回答
  • 2021-01-15 05:50

    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.
    0 讨论(0)
提交回复
热议问题