# How to unpack a vector to a struct / local variables

Is there a better way to write a function like this (which is called from an integrator so needs to have dx and x being Vector{Float64}'s and unpack them without excessive copying and mostly without all the magic numerical indexes that need to be maintained?

``````function eom!(dx,x,p,t,stage,scaling)
r  = x[1:3]
v  = x[4:6]
pv = x[7:9]
pr = x[10:12]
m  = x

rm = norm(r)
r3 = rm^3
r5 = rm^5

u  = normalize(pv)
At = stage.thrust / ( m * scaling.g_bar )

dx[1:3]   = v
dx[4:6]   = - r/r3 + At * u
dx[7:9]   = - pr
dx[10:12] = pv / r3 - 3 / r5 * r' * pv * r
dx    = - stage.thrust / stage.c

dx
end
``````

Clarification: `dx` and `x` needs to be `Vector{Float64}` or `AbstractVector{Float64}`? In second case there is a lot of thing that you can do. If it is `Vector` then it seems that the only thing you can do, is to reduce allocations with the help of `@.`.

Welcome to the forum! I think this is pretty much the prototypical use-case for: GitHub - jonniedie/ComponentArrays.jl: Arrays with arbitrarily nested named components.

2 Likes

Ultimately this is being called by DifferentialEquations.jl which will be wrapped by MINPACK.jl which uses `Vector{Float64}` but I don’t mind answering the question about `AbstractVector{Float64}` (and that might drive me to use something other than MINPACK.jl?)

I think, that marius311 already gave an answer for `AbstractVector`. Since DifferentialEquations.jl support abstract types, I think it makes sense to raise an issue in MINPACK.jl, to make type restrictions less tight (or you can fork this package and do it yourself).

Issue submitted to MINPACK,jl