简体   繁体   中英

Forcing function in ODE

I have a system of Ordinary Differential equation which contains a forcing function R_0. The forcing function has a formula to be calculated at each time step. I tried to use approxfunc() in R, but when I print R_0_matrix I got (?) on the R_0 column at each time point and I got this error message when I run R_0_value

 Error in xy.coords(x, y) : 
  (list) object cannot be coerced to type 'double'  

I don't know where is my mistake in the code,any help will be appreciated

Here is a part of my code:

# define model paramters
parameters <- c(N = 3.2*10^6,L =1000/15,dimm = 1/1.07, d_in = 75/365, d_treat0 = 2/52, p1 = 0.87, p2 = 0.08, k = 0.082, eta0 = 0.05, R_m =1.23,amp = 0.67,phi = 3/12)

# R_0 Forcing Function
t <- seq(0, 100, by = 0.1)
R_0 <-function(t,paramters){
    with(as.list(parameters),{
    R_0=R_m*amp*cos(2*pi*(t-phi))+R_m
    return(R_0)
    })
}

R_0_matrix <-cbind(t,R_0)
R_0_value<- approxfun(x=R_0_matrix[,1], y= R_0_matrix[,2], method="linear", rule=2)

R_0 is a function. So cbind(t, R_0) is probably not what you intended, since it tries to create a matrix where one column is numeric and the other is a function. See what happens, for example, if you type this into the console: cbind(1:10, function(x) {x}) . Probably you meant to do this:

R_0_t = R_0(t, parameters)

R_0_matrix <- cbind(t, R_0_t)
R_0_value <- approxfun(x=R_0_matrix[,1], y= R_0_matrix[,2], method="linear", rule=2)

Naming the function R_0 and then also calling the calculated object within the function environment R_0 may have caused some confusion. Even though the function creates an object called R_0 inside the function environment , the object R_0 that exists in the global environment is the function itself. To avoid confusion it's better to use different names for the function and any objects created inside the function environment.

Furthermore, the function does not return an object called R_0 to the global environment. It just returns the vector of numbers that result from evaluating the function R_0 . The name of this returned vector in the global environment is whatever you assign when you call the function ( R_0_t in the code sample above).

And just to check the approximation function:

plot(t[1:30], R_0_t[1:30], type="l", lwd=2)
lines(t[1:30], R_0_value(t[1:30]), col="red", lwd=6, lty=3)

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM