[R-sig-dyn-mod] Solving systems of differential equations in matrix form with deSolve

Thomas Petzoldt thom@@@petzo|dt @end|ng |rom tu-dre@den@de
Wed Apr 13 08:29:04 CEST 2022


Hi Nicola,

use of matrices in deSolve is quite popular and there are several ways 
to implement this. Here my standard example of a predator-prey model:

library(deSolve)
multi <- function(t, n, parms) {
   with(parms, {
     dn <- r * n  + n * (A %*% n)
     return(list(dn))
   })
}
times <- seq(from = 0, to = 500, by = 1)
init  <- c(prey1 = 1, prey2 = 1, pred1 = 2, pred2 = 2)

## Note: parms is a list, containing a vector and a matrix
parms <- list(
   r = c(r1 = 0.1, r2 = 0.1, r3 = -0.1, r4 = -0.1),
   ## only pairwise interactions:
   A = matrix(c(0.0, 0.0, -0.2,  0.0,     # prey 1
                0.0, 0.0,  0.0, -0.1,     # prey 2
                0.2, 0.0,  0.0,  0.0,     # predator 1; eats prey 1
                0.0, 0.1,  0.0,  0.0),    # predator 2; eats prey 2
              nrow = 4, ncol = 4, byrow = TRUE)
)
out <- ode(init, times, multi, parms)
plot(out)


The example is also found in the tutorial from a useR! conference: 
http://desolve.r-forge.r-project.org/user2014/tutorial.pdf in our new 
tutorial from last year: 
https://dynamic-r.github.io/hacking-limnology/#47 that contains also a 
matrix version of a 1D model


Another approach for more complex models, the so-called Gujer-Petersen 
matrix, is explained on pages 19-22 here: 
https://www.researchgate.net/publication/323535748_Using_R_for_Systems_Understanding_-_A_Dynamic_Approach

The latter approach is also supported by package rodeo. It can be 
installed from CRAN or from Github: https://dkneis.github.io/

Hope it helps,

Thomas


On 12.04.2022 at 17:04 Nicola Gambaro wrote:
> Dear all,
> 
> I have a model that is quite complicated to express as a list of single differential equations. It would be much easier to express it in matrix form, but I have not found an example of how deSolve can be used to do this.
> 
> Let us take as an example the simple linear system of ordinary differential equations
> 
> dY/dt = AY + F
> 
> where Y is the vector of the independent variables, A is the matrix of model parameters and F is the inhomogeneous part of the equations.
> 
> How do you go about using deSolve’s ode() function to solve this system?
> 
> Many thanks for your help in advance,
> Nicola
> 
-- 
Dr. Thomas Petzoldt
Technische Universitaet Dresden
Faculty of Environmental Sciences
Institute of Hydrobiology

https://tu-dresden.de/Members/thomas.petzoldt



More information about the R-sig-dynamic-models mailing list