Create view for an Array of FieldVector

Let’s say I have a struct that represents a point in 3D:

using StaticArrays
struct Point3D{T} <: FieldVector{3, T}

Then I generate some points like:

points = rand(Point3D{Float64}, 10)

If I am interested in the y-components only, I could for example do this:

pointsMatrix = reshape(reinterpret(Float64, points), 3, 10)
y = view(pointsMatrix, 2, :)

Is there a shorter / more direct way to do this (i.e. without reinterpret and reshape)?

I am not sure how this fits into views or not but one maybe easier way is to use StructArrays

using StructArrays
S = StructArray(points)

They are pretty performant even if it isn’t a view

Interesting, I am not familiar with StructArrays. I will have a look, but I do prefer a solution which doesn’t require an additional package.

Regarding your original solution, I think you cannot get around the reinterpret but you probably don’t need to reshape.

StructArrays will copy, though, it seems. In that case you might as well do

getindex.(points, 2)
1 Like