2015-07-10 354 views
1

規定差分方程像下面在MATLAB沒有問題,我可以用ODE45函數來解決它微分方程求解器(ODE45)在MATLAB

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

回答

2

您可以使用匿名FUNC而不是功能句柄@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];