function value VS function handle?

3 views (last 30 days)
kk1 = func1; % why kk1 is not a function handle?
p1 p2
kk2 = func1();% why kk2 is not a function handle either?
p1 p2
function out1 = func1()
function out2 = func2()
out2 = 10;
out1 = func2;

Accepted Answer

Walter Roberson
Walter Roberson on 17 Aug 2021

In MATLAB, when you name a true function in a context that is not one of:

  • a comment
  • a quoted string
  • parameter to a function being invoked in command syntax
  • question mark followed by the function name
  • immediately following a @
  • inside the body of an anonymous function being defined

Then, at the point that the function name is encountered, the function will be executed. If the function is the command in command/function equivalent mode then following expressions will be tokenized and passed as character vectors to the function. If the function is in an expression context and has () after it then the contents of the comma separated list will be executed and the results will be passed as parameters to the function. If the function is in expression syntax and is not followed by () then the function will be called with no parameters. (This last rule is what is happening in your example)

If, however, you have a function name immediately following a @ then a function handle is created. The rules of evaluation for function handles are close to those for true functions, except for the case where the variable holding the function handle is mentioned in an expression context without following (). In such a case, the function handle is not invoked, and instead the function handle is copied. So a function handle is like a pointer, with the rule that in command syntax with a following argument then it will be invoked, and in expression syntax with () it will be invoked, but in expression syntax with no () the pointer (handle) is the result rather than invoking it.

MATLAB does not return handles to functions unless @ is used.

out1 = func2;

at that point func2 is a true function and will be invoked as if you had used out1 = func2();

If you had used

out1 = @func2;

Then the handle to func2 would have been returned.

More Answers (1)

Eike Blechschmidt
Eike Blechschmidt on 17 Aug 2021
Edited: Eike Blechschmidt on 17 Aug 2021
With both statements you call the function. If you want the function handle you need to do:
kk1 = @func1;


Find more on Characters and Strings in Help Center and File Exchange




Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!