2010-02-13 50 views
9

我有以下功能:MATLAB:如何將參數傳遞給函數?

function ypdiff = ypdiff(t,y) 
    a = 0.01; 
    b = 0.1; 
    ypdiff(1) = -a*y(1)*y(2); 
    ypdiff(2) = b*y(1)*y(2)-b*y(2); 
    ypdiff(3) = b*y(2); 
    ypdiff = [ypdiff(1) ypdiff(2) ypdiff(3)]'; 

如果我想解決這個問題,我會打電話的ODE45功能如下:

[t y] = ode45(@ypdiff, [to tf], yo); 

但是,如果我想要一個參數傳遞給這個函數,我將如何使用ode45功能?具體來說,我想以下配方:

function ypdiff = ypdiff(t,y,u) 
    a = 0.01; 
    b = 0.1; 
    ypdiff(1) = -a*u*y(1)*y(2); 
    ypdiff(2) = b*u*y(1)*y(2)-b*y(2); 
    ypdiff(3) = b*u*y(2); 
    ypdiff = [ypdiff(1) ypdiff(2) ypdiff(3)]'; 

回答

8

您可以使用MATLAB中的anonymous function(類似於其他語言的lambda函數):

u = 1.2; 
[t y] = ode45(@(t, y) ypdiff(t, y, u), [to tf], yo); 
+0

大......非常感謝。但是,我不能得到它的工作,直到我刪除了':'字符 – Legend 2010-02-13 02:28:42

+0

是的,這是一個錯字,很抱歉;) – catchmeifyoutry 2010-02-13 02:29:48

+0

噢......謝謝澄清:) – Legend 2010-02-13 02:31:52