OrdinaryDiffEq vcat to make du

Hello,
In OrdinaryDiffEq.jl if we define the function as follows:

function f(du,u,p,t)
    x1 = u[1]
    x2 = u[2]
    dx1 = x2
    dx2 = -x1
    du = vcat(dx1,dx2)
    return du
end

the ODE solver fails to solve correctly and returns the initial solution.

But if we define the system as follows:

function f(du,u,p,t)

    x1 = u[1]
    x2 = u[2]
    dx1 = x2
    dx2 = -x1
    du[1] = dx1
    du[2] = dx2
    return du
end

The ODE solver works as expected.

Does anyone what causes this behaviour?

I am using the following code block to solve:

u0 = [1.0,0.0]
tspan = (0.0,10.0)
p = [1.0]
prob = ODEProblem(f,u0,tspan,p)
sol = solve(prob,Tsit5())

This is creating a new vector, not modifying du. It would need to be du .= vcat(dx1,dx2), though then you’d be allocating. The more efficient one is:

function f(du,u,p,t)

    x1 = u[1]
    x2 = u[2]
    dx1 = x2
    dx2 = -x1
    du[1] = dx1
    du[2] = dx2
    return nothing
end
1 Like