Octave 中的函数句柄

function handles in Octave

我对 Octave 中的函数(句柄)有疑问。 所以,我想调用一个函数,它接受两个变量和 returns 两个(实现有问题;但在这种情况下不相关)。

根据文档,这应该非常简单:

function [ret-list] = name (arg-list)

body

endfunction

我正在尝试以下操作:

function two_d_comp = twodcomp 
twodcomp.twoDperp=@perp;
                 ^
end

function twoDperp[vmag, vangle]=perp(x,y)
W = hypot(y,x);
vmag = y/W;
vangle = x/y;
end;

我将该函数保存在名为 twodcomp.m 的文件中。 当我按如下方式调用函数时:

[X, Y] = twodcomp.twoDperp(1,2)

Octave 吐出以下内容:

error: @perp: no function and no method found
error: called from
twodcomp at line 2 column 20

我设法通过删除输出参数 vmag 和 vangle 来消除错误,如下所示:

function twoDperp=perp(x,y)

但这显然不是我想要的。 你们碰巧对我做错了什么有一些指示吗?

干杯

您的初始函数 twodcomp:您不能将输出变量(在 = 之前)命名为与您的函数名称(在 = 之后)相同的名称。

然后,如果您想使用 @ 符号分配一个匿名函数 (MATLAB docs, Octave docs),您仍然可以传递所需的输入。

所以重写如下:

% Include empty parentheses after a function name to make it clear which is the output
function output = twodcomp()
    % Not sure why you're assigning this function to a struct, but
    % still give yourself the ability to pass arguments.
    % I'm assuming you want to use the output variable, 
    % and not reuse the main function name (again) 
    output.twoDperp = @(x,y) perp(x,y);                     
end

对于第二个函数,您只需删除输出参数前的 twoDperp。在您的问题中,您陈述了文档中的预期语法,但后来没有遵循它...

function [vmag, vangle] = perp(x,y)
    W = hypot(y,x);
    vmag = y/W;
    vangle = x/y;
end

现在可以这样使用了:

% Deliberately using different variable names to make it clear where things
% overlap from the function output. twodcomp output is some struct.
myStruct = twodcomp();
% The output struct has the field "twoDperp" which is a function with 2 outputs
[m, a] = myStruct.twoDperp(1,2);