2017-02-19 233 views
0

假設我們有以下功能:錯誤處理

function f=lorenz(t,x,a,b,c) 
    % solve differential equation like this 
    %dx/dt=a*(y-x) 
    %dy/dt=-x*z+b*x-y 
    %dz/dt=xy-c*z/3 
    f=zeros(3,1);% preallocate result 
    f(1)=a*(x(2)-x(1)); 
    f(2)=-x(1)*x(3)+b*x(1)-x(2); 
    f(3)=x(1)*x(2)-c*x(3)/3; 
    end 

運行這個程序,讓我們用下面的測試文件:

% test program 
x0=[-2 -3.5 21];% initial point 
a=input(' enter first coefficient : '); 
b=input(' enter second coefficient: '); 
c=input(' enter third coefficient : '); 
[t,x]=ode45(@(x) lorenz(x,a,b,c),[0 10],x0); 
plot(t,x(:,1),'r'); 
title(' solution of x part'); 
grid on 

我試圖傳遞參數給功能手柄,

test_program 
enter first coefficient : 10 
enter second coefficient: 28 
enter third coefficient : -8 

但它給了我以下錯誤:

Error using @(x)lorenz(x,a,b,c) 
Too many input arguments. 

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

Error in ode45 (line 113) 
[neq, tspan, ntspan, next, t0, tfinal, tdir, y0, f0, odeArgs, odeFcn, ... 

Error in test_program (line 6) 
[t,x]=ode45(@(x) lorenz(x,a,b,c),[0 10],x0); 

一個解決方案包括使用全局變量,像這樣:

function f=lorenz(t,x) 
    % solve differential equation like this 
    %dx/dt=a*(y-x) 
    %dy/dt=-x*z+b*x-y 
    %dz/dt=xy-c*z/3 
    global a 
    global b 
    global c 
    f=zeros(3,1);% preallocate result 
    f(1)=a*(x(2)-x(1)); 
    f(2)=-x(1)*x(3)+b*x(1)-x(2); 
    f(3)=x(1)*x(2)-c*x(3)/3; 
    end 

但隨後的時間太長運行。

還能如何解決這個問題?我想要通過不同的論點,如果我寫內部代碼這樣的事情這樣的

a=input('enter the coefficient : ') 

然後這將重複幾次。

+0

有什麼't'爲:

修復的方法是非常簡單的,加了t輸入呢?如果它是可選的,則將它移動到輸入參數列表的末尾('lorenz(x,a,b,c,t)')。 – EBH

+0

t爲輸出,或時間ODE45被callled –

回答

3

不要使用全局變量。在`洛倫茨(T,X,A,B,C)`

[t,x] = ode45(@(t,x) lorenz(t,x,a,b,c),[0 10],x0); 
+0

等待i可以錯過這部分 –

+0

感謝編輯後。 –

+0

,但有一個問題,它需要太多的時間 –