Search code examples
rloopsdifferential-equationsdesolve

deSolve & loop to solve a second order differential equation in R?


Hello dear community,

I am trying to solve a second order differential equation for quite some time now. The equation reads:

∂P/∂t = D * ∂^2P/∂x^2

I should run it for several P's; P1= df$col1, P2=df$col2, P3=df$col3 of a data frame and D would be df$col4 and x would be df$col5

I am trying to use "deSolve" for this, but at the moment I don't have much success. I would appreciate your input on how to solve a second order differential equation with R.


Solution

  • Let me try again. The boundary conditions - initial conditions for variable P would be; P1(t=0)= 0.4; P2(t=0)= 4.6; P3(t=0) = 0.37. I would like to think just in a code for the first P1 and then I could apply the same for the following columns of my data.frame.

    Using deSolve this is what I got so far: (P1=P)

    state <- c(P=0.4)
    t <- seq(0,100, by=0.1)
    J <- function (t, P, parameters) {
      deltax     <- c (1, rep(1, numboxes - 1)) ##doing a vector
      Fluxx       <- -D * diff (c(0,P,0) /deltax #First derivative
     dP    <- diff(Fluxx)/deltax # second derivative
      list(dP,Fluxx)
    } 
    

    **It would also be possible to solve the equation by applying an Eularian method and compute the change in concentration plus the divergence through time.