Reinterpreting vectors into vector of SVectors?

Hello! Suppose I have three vectors:

N = 100
x  = rand(N)
y  = rand(N)
z  = rand(N)

Is there any way in which I can reinterpret this into a vector of svector without having to perform allocations?

Kind regards

You will need to allocate a new Vector for storing the SVector of size 3N.

map(i->@SVector[x[i],y[i],z[i]], eachindex(x,y,z))

Think about how the memory looks right now: There is a block of size N somewhere in memory for each of x,y and z. A vector of SVector is a single block of length 3N.

It would be different if you had a matrix of size 3xN. This you could in principle reinterpret to a vector of SVector but I am unsure how it would work in practice.

1 Like

Okay, so in theory using a 3xN matrix, I would be able to:

  1. Reinterpret into 1D vectors for doing calculations without allocations
  2. Reinterpret into vector of SVector when I am done with calculations without allocations

Do I get it right?

Kind regards

Yes in principle. This works:

julia> N=100;
julia> M = rand(3,N);
julia> vec(reinterpret(SVector{3,Float64}, M)) # like a Vector{SVector{3, Float64}}
100-element reshape(reinterpret(SVector{3, Float64}, ::Matrix{Float64}), 100) with eltype SVector{3, Float64}:
...
julia> x = @view M[1,:] # like a Vector{Float64}

There are some caveat if you use views and reinterpreted arrays I think and the type is not Vector{...}.

In theory, you could do the following with the original code:

using StructArrays, StaticArrays
N = 100
x  = rand(N)
y  = rand(N)
z  = rand(N)
StructArray{SVector{3, Float64}}((x, y, z))

julia> StructArray{SVector{3, Float64}}((x, y, z))
100-element StructArray(::Vector{Float64}, ::Vector{Float64}, ::Vector{Float64}) with eltype SVector{3, Float64}:
 [0.9766031883579274, 0.9241366926864181, 0.567081609581811]
 [0.08470306282420592, 0.376441800265649, 0.938193146197035]
 [0.9165464733868074, 0.705275625598955, 0.3729177867932153]
 [0.8032446476318191, 0.4154235374182115, 0.08599130628048912]
 [0.6299647080569905, 0.2994029236057313, 0.5878713400559038]
5 Likes

Thanks! I would say that this is the solution. Being able to effortlessly and with no allocations, going from 1D vector to vector of svector (through StructArray) makes writing code much easier and when having to handle a specific problem and how to model it, I can now represent it exactly how I please.

And thanks to @abraemer as well for taking the time to explain reinterpret to me.

Kind regards

2 Likes