Exclamation mark in Julia "!" after function in scripts

160 views Asked by At

I am trying to save multiple solutions of my ODE in an Array. Right now this is what I got:

sols = []
for i in 1:numSim
  if solver == "Rosenbrock23"
    solution = solve(odeprob, Rosenbrock23())
    append!(sols, solution)
  end
end

As you can see I only want to append to this Array, if a certain ode solver is used. However, the "append!" statement neglects this statement and runs every iteration of the loop. I tried preallocating the array sol, to use a statement like this:sols[i] = solution But here im struggling with the type declaration of the array sol.

I tried sols = zeros(length)

and then sols[i] = solution

However solution is of type ODESolution and can not be converted to Float64

1

There are 1 answers

0
Shayan On

Please provide adequate information to get an exact answer. I can't reproduce your problem since you didn't mention what is odeprob or the value of numSim. Since you declared sols = [] then the eltype of sols should be Any; hence it should be capable to contain any element.
However, I can replicate the code in the official doc (Example 1 : Solving Scalar Equations (ODE)), and combine it with your approach:

using DifferentialEquations

f(u,p,t) = 1.01*u
u0 = 1/2
tspan = (0.0,1.0)
odeprob = ODEProblem(f,u0,tspan)

sols = []
numSim = 2
solver = "Rosenbrock23"
for i in 1:numSim
  if solver == "Rosenbrock23"
    solution = solve(odeprob, Rosenbrock23())
    append!(sols, solution)
  end
end

Then if I call the sols variable:

julia> sols
22-element Vector{Any}:
 0.5
 0.5015852274675505
 0.5177172276935554
 0.5423763076371255
 0.5852018498590001
 0.6425679823795596
 0.7275742030693312
 0.835930076418226 
 0.9846257728490266
 1.1713401410831334
 1.3738764155543854
 0.5
 0.5015852274675505
 0.5177172276935554
 0.5423763076371255
 0.5852018498590001
 0.6425679823795596
 0.7275742030693312
 0.835930076418226
 0.9846257728490266
 1.1713401410831334
 1.3738764155543854