首页 文章

运行时Matlab错误

提问于
浏览
-2

我试图在Matlab中实现以下代码:

v0=eps;
t0=0; tf=10;
[t,v]=ode45(@const_pow, [t0 tf], v0);

而const_pow函数是:

function f=const_pow(t,v)
   f=(P/v-F0-c*v^2)/m; 
end

在运行程序时,出现以下错误:

Error using ==> odearguments at 103

CONST_POW returns a vector of length 0, but the length of initial 
conditions vector is 1. The vector returned by CONST_POW and the   
initial conditions vector must have the same number of elements.

有关错误可能位置的任何建议吗?

1 回答

  • 0

    根据您的评论,您将全局定义一些变量 . 要在 const_pow 中访问它们,您需要告诉该函数使用全局变量,例如:

    function f=const_pow(t,v)
       global P F0 c m
       f=(P/v-F0-c*v^2)/m; 
    end
    

    如果不这样做,该函数将不会触及全局变量(这是为了阻止您意外更改其值) . 例如:

    function f=const_pow(t,v)
       global P F0 c
       m = 23.7; % this does not change the global value of m
       f=(P/v-F0-c*v^2)/m; 
    end
    

    在不使用全局变量的情况下传递大量变量的替代方法是使用所需数据定义结构:

    data.P = % initial values
    data.F0 = 
    data.c = 
    data.m =
    

    如果有多个选项,这也可以为您提供更多灵活性 . 或者,您可以直接传递变量 . 要使用 ode45 执行此操作,您需要使用匿名函数parameterize该函数:

    function f=const_pow(t,v,P,F0,c,m)
        % and so on
    end
    

    预定义为 P,F0,c,m

    odefun = @(t,v) const_pow(t,v,P,F0,c,m); % anonymous function
    

    然后:

    [t,v]=ode45(odefun, [t0 tf], v0);
    

相关问题