Save access to vector elements in struct

I’d like to have some values in an array:

v = SVector{4, Float64}(rand(4)...)

and I want to modify (add) each element in an iterative process. But the modification occurs “somewhere else”: right now, those 4 values are scattered across 2 instances of a type with two fields (2x2=4). When I need this vector (for HCubature integration) I go and collect the values from the fields in my types and build the vector. This is a bit expensive.

I could restructure the whole thing so the modification part would act on this v vector instead of my types, but that really doesn’t make any sense from a structural point of view.

Or… I could maybe save a reference to the elements of this vector in my types:

using StaticArrays
struct V
    i::SubArray{Float64,1,MArray{Tuple{4},Float64,1,4},Tuple{UnitRange{Int64}},true}
end
struct T
    v::MVector{4, Float64}
    x::V
end

v = MVector{4, Float64}(rand(4)...)
t = T(v, V(view(v, 1:1)))
t.x.i[] += 2

This way I’ll always have both: a fully built vector and its modifiable elements where I need them.

Sounds good, or am I missing something?

This doesn’t sound expensive?

The function hcubature integrates needs to build a vector (albeit an SVector) of those values. I thought that in the same lines as “avoid constructing arrays inside for loops”, I should try and avoid that too?

This sounds way more complicated than it needs to be, but perhaps I just don’t understand your application. Why not just use an MVector and mutate it? Or use an SVector and replace individual elements using StaticArrays.setindex ?

No, SVectors of bitstypes are themselves bitstypes and therefore pretty much free, and constructing new ones inside a loop is generally fine.

2 Likes

Just to answer this: the application doesn’t act on the vector. It acts on my types. At the same time, I want to integrate some of the values inside my types. The integration needs to return a vector. Therefore I need to convert my structure with my values peppered around my structure to a contingent vector.

Well! Then there’s no point in me doing that then. I just thought that reallocating a vector each time was expensive (for each iteration hcubature calls the function it integrates).

That doesn’t apply to StaticArrays, tuples, and similar types.

2 Likes