Octave 中的 @ 符号是做什么用的?

What is the @ symbol used for in Octave?

Octave 中的 @ 符号有什么用?

例如代码中:

[theta, cost] = fminunc(@(t)(costFunction(t, X, y)), initial_theta, options);

我大致了解代码的作用,但不明白 @(t) 的作用。我查看了八度文档,但 @ 符号似乎很难搜索。

@在匿名函数定义中的虚拟变量之前,例如:

f = @(x) x.^2;
y=[1:3];
f(y)

returns

1 4 9

快速查看 help fminunc 显示您示例中的 FCN 是 @(t)(costFunction(t, X, y))

从控制台:

octave:1> help @

 -- @
     Return handle to a function.

     Example:

          f = @plus;
          f (2, 2)
          =>  4

     (Note: @ also finds use in creating classes.  See manual chapter
     titled Object Oriented Programming for detailed description.)

     See also: function, functions, func2str, str2func.

手册中的更多信息:https://octave.org/doc/interpreter/Function-Handles.html


在您的特定代码中,“@”语法用于创建函数的 "on-the-spot" 实现(以匿名函数的形式),该函数采用 single 参数,而不是 costFunction 一个所需的三个参数。这是因为 fminunc 需要一个接受单个参数的函数,因此可以有效地 'wraps' 将更复杂的函数转换为与 fminunc 兼容的更简单的函数。