简体   繁体   中英

Differential equation solver (ODE45) in MATLAB

Defining a differential equation like below has no problem in MATLAB and I can use ODE45 function to solve it

# 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];

However, if I add new functions based on x , ODE45 fails to work

# 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];

The error is

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

You can use an anonymous function instead of the function handle @fun . Then you can define the variables A1 and A2 inside the anonymous function like this:

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

Note that the function passed to ode45 needs two arguments. Since you don't need x in your function fun you just don't need to pass it in the anonymous function.


The complete code can be defined in a single file like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM