Changing parameter values ​​in a time step in deSolve

I am trying to solve ODE in R using deSolve. In the following code, I expected the parameter to gamma0take the values ​​5 in step 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, and 0 otherwise. However, it print(gamma0)shows that it gamma0remains at 0.

Here is my ODE:

library(deSolve) 
param <- c(a = 0.1, b = 1) 
yini <- c(alpha0 = 6, beta0 = 2) 

mod <- function(times, yini, param) { 

  with(as.list(c(yini, param)), { 

    gamma0 <- ifelse(times %in% seq(0,10,1), 5, 0) 

    ## print(gamma0) 

    dalpha0 <- - a*alpha0 + gamma0 
    dbeta0 <- a*alpha0 - b*beta0 
    return(list(c(dalpha0, dbeta0))) 

  })} 

times <- seq(from = 0, to = 10, by = 1/24) 
out <- ode(func = mod, times = times, y = yini, parms = param) 
plot(out, lwd = 2, xlab = "day")

What am I doing wrong?

+4
source share
2 answers

This is a really simple modification to your function. If you are interested in knowing what you are doing wrong, you can look below.

mod <- function(times, yini, param) { 

  dt = times[2] - times[1]
  with(as.list(c(yini, param)), { 

    gamma0 <- ifelse(times <= 10*dt, 5, 0) 

    ## print(gamma0) 

    dalpha0 <- - a*alpha0 + gamma0 
    dbeta0 <- a*alpha0 - b*beta0 
    return(list(c(dalpha0, dbeta0))) 

  })} 

EDIT

Same as G5W answer, the problem is what you are comparing timeswith.

When you write

times %in% seq(0,10,1)

. times.

, 10 , -, dt.

:

gamma0 times , 5 11 (10) , times? 5 ?

+4

. print(gamma0), 5, 513 . , , , .

() print(gamma0), :

cat("g:", gamma0, "  t:", times, "\n")

. , 0. seq(0,10,1) gamma0 5. . , seq(from = 0, to = 10, by = 1/24), , , 5 5. ode - (?), , . , 241 - . 515 . , out 241 .

, , , ode times. . times .

gamma0 <- ifelse(times %in% seq(0,10,1), 5, 0) 

11 - . .

+3

Source: https://habr.com/ru/post/1673145/


All Articles