运行时出现Matlab错误

运行时出现Matlab错误,matlab,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

我尝试在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
然后:


这就是你的
const\u pow
功能的全部吗?您还没有定义其中一半的变量,也没有使用
t
。所有变量都是全局定义的。我在主函数本身中提供了所有d变量数据。f基本上是dv/dt(加速)全局变量通常是个坏主意,而且除非在函数中声明它们为全局变量,否则不能在函数中访问它们。参见答案。嗨,我把全局变量也放在const_pow函数中函数f=const_pow(t,v)global P c F0 m f=(P/v-F0-c*v^2)/m;结束在
const_pow
中放置一个断点,并再次检查
f
是否如您所期望的那样出现。一种可能的解释是,您的一个全局变量为空,导致
f
被传递回为空。我还是不明白你为什么不在这个函数中使用
t
[t,v]=ode45(odefun, [t0 tf], v0);