2013-08-31 165 views
0

我有3個短的函數,我在Matlab裏面用3個獨立的m文件編寫。從另一個函數內部調用一個函數?

主函數稱爲F_並接受一個輸入參數並返回一個包含3個元素的向量。

從F_輸出的元素1和2(應該是)使用其他2 m個文件中的函數進行計算,現在讓我們稱它們爲theta0_和theta1_。

下面的代碼:

function Output = F_(t) 

global RhoRF SigmaRF 

Output = zeros(3,1); 

Output(1) = theta0(t); 
Output(2) = theta1(t) - RhoRF(2,3)*sqrt(SigmaRF(2,2))*sqrt(SigmaRF(3,3)); 
Output(3) = -0.5*SigmaRF(3,3); 

end 

function Output = theta0_(t) 

global df0dt a0 f0 SigmaRF 

Output = df0dt(t) + a0 + f0(t) + SigmaRF(1,1)/(2*a0)*(1-exp(-2*a0*t)); 

end 

function Output = theta1_(t) 

global df1dt a1 f1 SigmaRF 

Output = df1dt(t) + a1 + f1(t) + SigmaRF(2,2)/(2*a1)*(1-exp(-2*a1*t)); 

end 

我創建的句柄這些功能如下:

F = @F_; 
theta0 = @theta0_; 
theta1 = @theta1_; 

當我運行F_通過它與t任何價值,我得到以下錯誤處理:

F_(1) 
Undefined function 'theta0' for input arguments of type 'double'. 

Error in F_ (line 9) 
Output(1) = theta0(t); 

請協助。我在這裏做錯了什麼?

我只希望能夠從另一個內部調用一個函數。

+3

您將其定義爲'theta0_'並稱之爲'theta0'。另外,您不需要通過處理來調用它。 – Oleg

回答

2

每個函數都有自己的工作區,並且由於您沒有在函數F_的工作區內創建theta0,所以會出現錯誤。

很可能您不需要額外的間接級別,您可以在函數中使用theta0_

如果您確實需要間接的額外層次,你有幾種選擇:

  • 傳遞函數句柄作爲參數:

    function Output = F_ (t, theta0, theta1) 
        % insert your original code here 
    end 
    
  • F_嵌套函數:

    function myscript(x) 
    
    % There must be some reason not to call theta0_ directly: 
    if (x == 1) 
        [email protected]_; 
        [email protected]_; 
    else 
        [email protected]_; 
        [email protected]_; 
    end 
    
        function Output = F_(t) 
         Output(1) = theta0(t); 
         Output(2) = theta1(t); 
        end % function F_ 
    
    end % function myscript 
    
  • 使函數處理全局。您必須在F_以及您設置theta0theta1這兩者中執行此操作。並且確保你不要在程序中的其他地方使用具有相同名稱的全局變量。

    % in the calling function: 
    global theta0 
    global theta1 
    
    % Clear what is left from the last program run, just to be extra safe: 
    theta0=[]; theta1=[]; 
    
    % There must be some reason not to call theta0_ directly. 
    if (x == 1) 
        [email protected]_; 
        [email protected]_; 
    else 
        [email protected]_; 
    end 
    
    F_(1); 
    
    % in F_.m: 
    function Output = F_(t) 
        global theta0 
        global theta1 
        Output(1)=theta0(t); 
    end 
    
  • 使用evalin('caller', 'theta0')從內F_。 如果您從其他地方致電F_,則可能會導致問題,其中theta0未被聲明或者甚至用於不同的事情。

+1

+1爲全面的選項列表。 –

+0

嗨,謝謝你的詳細回覆。幾個問題,你是什麼意思的間接?你的意思是我可以使用函數名('theta0_'和'theta1_')從'F_'調用函數,而不必使用函數句柄('theta0'和'theta1')?也許我只是沒有得到全局變量,但是現在我的工作中,基本工作空間中有變量,我希望這些函數不必將它們傳遞到函數中就可以使用,例如'df0dt a0 f0 SigmaRF'。我在theta函數中完成的方式是否正確? – Fayyaadh

+0

全局聲明看起來不錯,但是您還必須在基本工作空間中將它們聲明爲全局聲明。或者你可以在你的函數中使用'df0dt = evalin('base','df0dt');'來訪問基本工作區。通過間接我的意思是直接調用'theta0_'的方法是輸入'theta0_'。如果事先不知道你需要調用什麼函數,你可以添加一個間接級別:你聲明一個函數句柄並將其設置爲正確的函數,並且在調用站點處調用句柄指向的函數。這是你用'theta0'完成的,它指的是'theta0_',但是可以改變。 – mars

相關問題