Updating a static array, in a nested function without making a temporary array?

have been banging my head against a wall trying to use static arrays in julia.

They are fast but updating them is a pain. This is no surprise, they are meant to be immutable!

But it is continuously recommended to me that I use static arrays even though I have to update them. In my case, the static arrays are small, just length 3, and i have a vector of them, but I only update 1 length three SVector at a time.
thanks

some example please?..

Nowadays you can often get away with converting to MVector, modifying the MVector, and then converting back to SVector, without incurring additional costs (like dynamic allocation). For example,

using StaticArrays
using BenchmarkTools

function f(x)
    y = MVector(x)
    y[3] = 1
    SVector(y)
end
julia> @btime f(x) setup = (x = rand(SVector{3}))
  1.651 ns (0 allocations: 0 bytes)
3-element SArray{Tuple{3},Float64,1,3} with indices SOneTo(3):
 0.9714613510548404
 0.33570294516112464
 1.0
3 Likes

Setfield.jl might help

1 Like

Have you tried setindex (no !)?

julia> v = @SVector rand(3)
3-element SArray{Tuple{3},Float64,1,3} with indices SOneTo(3):
 0.12239428476400516
 0.32772745126065295
 0.43563988269786025

julia> v_ = setindex(v, 1.5, 2)
3-element SArray{Tuple{3},Float64,1,3} with indices SOneTo(3):
 0.12239428476400516
 1.5                
 0.43563988269786025
1 Like