Matlab运行时出现错误



我试图在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.

有什么建议的错误可能在哪里?

从您的评论中,您正在全局定义一些变量。为了在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执行此操作,需要使用匿名函数对函数进行参数化:

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);

相关内容

最新更新