2017-07-19 116 views
-1

我有一個關於Octave中的函數(句柄)的問題。 所以,我想調用一個函數,它接受兩個變量並返回兩個變量(實現有問題;但在這種情況下不相關)。Octave中的函數句柄

根據文檔這應該是很簡單的:

函數[RET-列表] =名(精氨酸 - 列表)

endfunction可寫

我請嘗試以下操作:

function two_d_comp = twodcomp 
[email protected]; 
       ^
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) 

倍頻吐出以下:

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

我管理通過去除輸出參數VMAG和V形角度,以除去錯誤,如下所示:

function twoDperp=perp(x,y) 

但這顯然不是我想要的。 你們是否碰巧指出我做錯了什麼?

乾杯

+3

由於文檔指定語法:'function [ret-list] = name(arg-list)',用這個'function twodcomp = twodcomp'函數的輸出是twodcomp,你函數的名字也是'twodcomp'。沒有輸入參數。在第二個函數中,'function twoDperp [vmag,vangle] = perp(x,y)''twoDperp [vmag,vangle]'不是一個有效的語法。它可以是'[vmag,vangle]'或'twoDperp'。從你的代碼看,你似乎想使用'[vmag,vangle]'。我也不知道你想用'[email protected];' –

+0

做什麼,它們被稱爲匿名函數,我在我的答案中已經鏈接到MATLAB和Octave文檔。 – Wolfie

回答

1

您最初的功能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);