首页 文章

Octave中的函数句柄

提问于
浏览
-1

我对Octave中的函数(句柄)有疑问 . 所以,我想调用一个函数,它接受两个变量并返回两个(实现是错误的;但在这种情况下不相关) .

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

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)

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

干杯

1 回答

  • 1

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

    然后,如果要使用 @ 表示法分配匿名函数(MATLAB docsOctave 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);
    

相关问题