function value VS function handle?

조회 수: 2 (최근 30일)
cui,xingxing
cui,xingxing 2021년 8월 17일
답변: Walter Roberson 2021년 8월 17일
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()
disp("p1");
function out2 = func2()
disp("p2")
out2 = 10;
end
out1 = func2;
end

채택된 답변

Walter Roberson
Walter Roberson 2021년 8월 17일

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.

추가 답변 (1개)

Eike Blechschmidt
Eike Blechschmidt 2021년 8월 17일
편집: Eike Blechschmidt 2021년 8월 17일
With both statements you call the function. If you want the function handle you need to do:
kk1 = @func1;

카테고리

Help CenterFile Exchange에서 Whos에 대해 자세히 알아보기

제품


릴리스

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by