2016-10-13 145 views
0

我試圖將deSolve包用於一組ODE,並將方程作爲輔助變量。在衍生物的數量與初始條件向量長度不相同的情況下,我總是收到錯誤。我應該改變什麼?用解決方案中的R解決衍生產品錯誤

# rm(list=ls()) 
library(deSolve) 

exponential=function(t,state,parameters){ with(as.list(c(state,parameters)), { 

    #Aux. Var. 
    fX2 = pmax(0,1-(1-(d2/r12)*(X2/K2))) 
    fX1 = X1/(X1+k1); 

    # equations (ODE) 
    dX1 = C-((d1)*(X1))-(r12)*(X2)*fX2*fX1 # differential equaion 
    dX2 = r12*(X2)*fX2*fX1-((d2)*(X2)) 

    return(list(c(dX1, dX2))) 
    }) 
} 

# -- RUN INFORMATION 

# Set Initial Values and Simulation Time 
state = c(X1=2,X2=0.01,K2= 10) 
times=0:100 

# Assign Parameter Values 
parameters = c(d1=0.001, d2=0.008, r12=0.3,C=0.5,k1= 0.001) 

for (i in 1:length(times)){ 
    out= ode(y=state,times=times,func=exponential,parms=parameters) 
    } 

Error in checkFunc(Func2, times, y, rho) : 
    The number of derivatives returned by func() (2) must equal the length of 
the initial conditions vector (3)** 

回答

1

這個錯誤來自於你的定義函數的return: 你輸入參數y長度爲3,但只退回2個值回來了,這就是錯誤。你可以用

return(list(c(X1, X2, K2))) 

解決您的問題,另一種可能性是採取K2的參數,那麼你的舊return是正確的。你必須決定K2是一個變量還是一個參數。

和順便說一句:爲什麼一個for循環與時間?在我看來,這不是必要的,因爲ODE在您提交給ode函數的時間間隔內解決。

out= ode(y=state,times=times,func=exponential,parms=parameters)