2013-08-31 269 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

相关问题