Solving ODE with deSolve in R- number of derivatives error

﹥>﹥吖頭↗ 提交于 2019-12-25 04:23:15

问题


I am trying to use the deSolve package for a set of ODE's with equations as auxiliary variables. I keep getting the error where the number of derivatives isn't the same length as the initial conditions vector. What should I change?

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


The error comes from the return in your defined function: Your input parameter y has length 3, but you only return 2 values back, that's the error. You can solve your problem with

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

Another possibility is to take K2 to the parameters, then your old return was right. You have to decide if K2 is a variable or a parameter.

And BTW: Why a for loop with the time? In my opinion that is not necessary, because the ODEs are solved in the timeinterval you submitted to the odefunction.

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


来源:https://stackoverflow.com/questions/40025139/solving-ode-with-desolve-in-r-number-of-derivatives-error

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!