Resizing ODE integrator of type matrix

I’m trying to resize the integrator in and ODE solved with solve where u is a matrix. I also found a post similar to this (Resizing ODE integrator with matrix or VectorOfArray initial condition) but I want to do it with a Matrix instead of an ElasticArray. I’d like to fix the code

using DifferentialEquations
function odefun!(du, u, p, t)
    du[:, 1] .= rand(2)
    du[:, 2] .= rand(2)
    du[:, 3] .= rand(2)
    du[:, 4] .= rand(2)
    nothing 
end
u0 = [0.0 0.0 0.0 0.0; 0.0 0.0 0.0 0.0]
tspan=(0.0,1.0)
prob=ODEProblem(odefun!, u0, tspan)
integrator = init(prob,Tsit5())
resize!(integrator, (2,3))

Unfortunately, when using resize!(integrator, (2,3)) I get the error

ERROR: MethodError: no method matching resize!(::Matrix{Float64}, ::Tuple{Int64, Int64})
Closest candidates are:
  resize!(::OrdinaryDiffEq.AbstractNLSolver, ::Any, ::Int64)
   @ OrdinaryDiffEq ~/.julia/packages/OrdinaryDiffEq/Y6bIX/src/nlsolve/utils.jl:453
  resize!(::OrdinaryDiffEq.AbstractNLSolverCache, ::Any, ::Any, ::Int64)
   @ OrdinaryDiffEq ~/.julia/packages/OrdinaryDiffEq/Y6bIX/src/nlsolve/utils.jl:462
  resize!(::StochasticDiffEq.SDEIntegrator, ::Any, ::Any)
   @ StochasticDiffEq ~/.julia/packages/StochasticDiffEq/aR0ZE/src/integrators/integrator_interface.jl:91

and when changing it to resize!(integrator, 3) I get the error

ERROR: MethodError: no method matching resize!(::Matrix{Float64}, ::Int64)
Closest candidates are:
  resize!(::BitVector, ::Integer)
   @ Base bitarray.jl:814
  resize!(::LoopVectorization.LoopOrder, ::Int64)
   @ LoopVectorization ~/.julia/packages/LoopVectorization/tIJUA/src/modeling/graphs.jl:439
  resize!(::Vector, ::Integer)
   @ Base array.jl:1312

Do you have any idea how to fix it?

I used ElasticMatrix in that thread exactly so that resize! works - Matrix isn’t mutable. Do you have a particular reason to want to only use Matrix?

Array{T,N} where N is not 1 cannot currently be resized (in-place); resize! is even documented in Base for Vector in particular. ElasticArrays.jl exists exactly to implement resizing along the last dimension, which is the only efficient dimension for resizing column-major arrays.

1 Like

I wanted to keep the Type the same for the following computations. But since apparently it’s not possible with Matrix I changed it now to ElasticMatrix which works :slight_smile:

2 Likes

It’s not currently implemented. It’s hypothetically possible to expand and move the underlying linear buffer (currently Memory) for higher dimension Arrays like Vectors do now. Before the Memory implementation change, this was brought up but rejected for inhibiting compiler optimizations that rely on the linear buffer to stay in the same place and thus the same size. It was not explicitly explained if Vectors lose those optimizations.

resize! for multidimensional arrays · Issue #37900 · JuliaLang/julia

1 Like