MATLAB中的微分方程求解器(ODE45)

时间:2015-07-10 11:57:54

标签: matlab ode45

定义如下的微分方程在MATLAB中没有问题,我可以使用ODE45函数来解决它

# example.m
x = pi / 2;
x_span=[0 pi/2];
ic=[0 1];
[X OUT] = ode45(@fun,x_span,ic)

#fun.m
function out=fun(x,s)
y1 = s(1)
y2 = s(2)
out=[y2;x*y1];

但是,如果我根据x添加新功能,则ODE45无法正常工作

# example.m
x = pi / 2;
A1 = sin(x);
A2 = sin(x)+1;
x_span=[0 pi/2];
ic=[0 1];
[X OUT] = ode45(@fun,x_span,ic)

#fun.m
function out=fun(A1,A2,s)
y1 = s(1)
y2 = s(2)
out=[y2;A1*y1+A2];

错误是

??? Input argument "s" is undefined.

Error in ==> fun at 2
y1 = s(1)

Error in ==> odearguments at 98
f0 = feval(ode,t0,y0,args{:});   % ODE15I sets args{1} to yp0.

Error in ==> ode45 at 172
[neq, tspan, ntspan, next, t0, tfinal, tdir, y0, f0, odeArgs, odeFcn, ...

Error in ==> example2 at 8
[X OUT] = ode45(@fun,x_span,ic)

1 个答案:

答案 0 :(得分:2)

您可以使用匿名函数而不是函数句柄@fun。然后,您可以在匿名函数中定义变量A1A2,如下所示:

[X OUT] = ode45(@(x,s)fun(A1,A2,s),x_span,ic)

请注意,传递给ode45的函数需要两个参数。由于您在函数x中不需要fun,因此您无需在匿名函数中传递它。

完整的代码可以在单个文件中定义,如下所示:

function ode_Tb
x = pi / 2;
A1 = sin(x);
A2 = sin(x)+1;
x_span=[0 pi/2];
ic=[0 1];
[X OUT] = ode45(@(x,s)fun(A1,A2,s),x_span,ic)

function out=fun(A1,A2,s)
y1 = s(1)
y2 = s(2)
out=[y2;A1*y1+A2];