ODEs using Element-wise vector multiplication

Hi All,

I’m new to Julia. I would like to solve a series of ODEs but noticed the solution does not update when I use element-wise vector multiplication (see the code snippet and plot below). Why does f1! solve correctly whereas f2! doesn’t?

Code Snippet

using DifferentialEquations
using Plots

w = [0.1 0.2];

# Scalar multiplication
function f1!(du, u, p, t)
    du[1] = u[1]*w[1];
    du[2] = u[2]*w[2];
end

# Element-wise vector multiplication
function f2!(du, u, p, t)
    du = u.*w;
end

u0 = [1.0, 2.0];
tspan = (0.0, 1.0);

prob1 = ODEProblem(f1!, u0, tspan);
sol1 = solve(prob1);

prob2 = ODEProblem(f2!, u0, tspan);
sol2 = solve(prob2);

plot(sol1,
     labels=["f1! S1" "f1! S2"],
     color=[:red :blue],
     linestyle=:solid);

plot!(sol2,
      labels=["f2! S1" "f2! S2"],
      color=[:red :blue],
      linestyle=:dash);

savefig("C:\\Users\\jonat\\Desktop\\result.png");

Result
result1

function f2!(du, u, p, t)
    du .= u.*w;
end

Mutate, don’t make a new vector if you’re using the mutating syntax.

1 Like

Ah, I see. Thank you for the help!