Side question: why a vector of MVector
? If you have an array of SVector
it will typically be more efficient and you can still mutate the array contents:
julia> using StaticArrays
julia> vec = zeros(SVector{3, Float64}, 4)
4-element Vector{SVector{3, Float64}}:
[0.0, 0.0, 0.0]
[0.0, 0.0, 0.0]
[0.0, 0.0, 0.0]
[0.0, 0.0, 0.0]
julia> vec[1] = @SVector[1,2,3];
julia> vec
4-element Vector{SVector{3, Float64}}:
[1.0, 2.0, 3.0]
[0.0, 0.0, 0.0]
[0.0, 0.0, 0.0]
[0.0, 0.0, 0.0]
This is analogous to the fact that numbers are immutable (you can’t change the value of 4
), but if you have an array of numbers you can mutate the container to replace an element with a different number.
PS. vec[1] = [1,2,3]
also works, but unnecessarily heap-allocates a Vector
for the right-hand-side before converting it to an SVector
to store in the array vec
.
This approach would also fail in reality because I am not assigning [1,2,3], but a vector that is always the same vector, just with different values.
PPS. If the vector is an SVector
, you don’t need to worry about pre-allocating it and then overwriting it in place. Part of the whole point of using StaticArrays is that “allocating” them as local variables is essentially free, in the same way that you don’t worry about “allocating” new integers when you compute n = n + 1
in a loop.