Search code examples
matlabfunctionhandle

What does `@(x) myfun(x, F_index)` means in Matlab?


What does @(x) myfun(x, F_index) means in MATLAB? What does it call and return?

For example in this application:

fmincon(@(x) myfun(x, F_index), ...)

Please provide more examples and explain them if possible.


Solution

  • It is an anonymous function, which is a function that is not stored in a program file, but is associated with a variable whose data type is function_handle. Anonymous functions can accept inputs and return outputs, just as standard functions do. However, they can contain only a single executable statement. For example, create a handle to an anonymous function that finds the square of a number:

        function out=powerplus1(x,dat)
        out=x^2+dat;
         end
    

    In another file you write

    dat=1;
    sqr = @(x) powerplus1(x,dat);
    a = sqrplusone(5)
    

    Then a will be 26.

    Variable sqrplusone is a function handle. The @ operator creates the handle, and the parentheses () immediately after the @ operator include the function input arguments. This anonymous function accepts a single input x, and implicitly returns a single output, an array the same size as x that contains the squared plus one values. Find the square plus one of a particular value (5) by passing the value to the function handle, just as you would pass an input argument to a standard function.

    a = sqrplusone(5)
    a =
       26