簡體   English   中英

從另一個函數內部調用函數?

[英]Calling a function from inside another function?

我有3個簡短的函數,我在Matlab中的3個獨立的m文件中編寫。

main函數名為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_;

當我使用任何t值通過它的句柄運行F_時,我得到以下錯誤:

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

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

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

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

每個函數都有自己的工作空間,因為您沒有在函數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 ) theta0=@theta0_; theta1=@theta1_; else theta0=@otherfunction_; theta1=@otherfunction_; 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 ) theta0=@theta0_; theta1=@theta1_; else theta0=@otherfunction_; end F_(1); % in F_.m: function Output = F_(t) global theta0 global theta1 Output(1)=theta0(t); end 
  • F_里面使用evalin('caller', 'theta0') 如果你從其他地方調用F_ ,那里可能會導致問題,其中未聲明theta0或甚至用於不同的東西。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM