How to use DifferentialEquations with complicated equations

It seems like a lot of your confusion is related to defining and calling functions, not from DifferentialEquations. In your last example, you are assigning a function object (a.k.a. an anonymous function) to the elements of the vector du, which is not what you want. I’m guessing what you want to do is to call those functions (Basal and Consumer) and assign the values they return to du[1] and du[2]. I think you should work through the functions section in the manual and make sure you have a good grasp of defining, calling, and composing functions before trying to make them work in DifferentialEquations.

When you come back to this problem, here’s some code that may help you get started, based on this Lotka-Volterra system from Wikipedia. Notice how I have a helper function interaction which is defined outside, but then called within, the main simulation function:

using DifferentialEquations
using Plots
using LinearAlgebra

function interaction(B, i, p)
    return 1 - dot(B, p[:A][i, :]) / p[:K][i]
end

function lotka_volterra!(dB, B, par, t)
    for i in 1:length(B)
        dB[i] = par[:r][i] * B[i] * interaction(B, i, par)
    end
end

A = [1 1.09 1.52 0;
     0 1 0.44 1.36;
     2.33 0 1 0.47;
     1.21 0.51 0.35 1]
r = [1, 0.72, 1.53, 1.27]
K = ones(4)

params = Dict(:A => A, :r => r, :K => K)
B0 = [0.1, 0.5, 0.05, 0.4]
tspan = (0.0, 1000.0)
prob = ODEProblem(lotka_volterra!, B0, tspan, params)
sol = solve(prob)
plot(sol)
5 Likes