StaticArrays documentation gives a way to convert a 2D array of values to a 1D array of StaticArrays: reinterpret(SVector{N,T}, vec(x))
. However I cannot find it anywhere how to perform the opposite conversion - from a 1D array of StaticArrays to 2D array of plain values, also without copying any data. Is it possible at all?
Yes, you can do the reverse operation by reinterpreting as T and then reshaping. There’s also no need to call vec(x)
:
julia> x = rand(2, 3)
2×3 Array{Float64,2}:
0.0929609 0.827564 0.622823
0.314605 0.221642 0.066153
julia> y = reinterpret(SVector{2, Float64}, x)
1×3 reinterpret(SArray{Tuple{2},Float64,1,2}, ::Array{Float64,2}):
[0.0929609, 0.314605] [0.827564, 0.221642] [0.622823, 0.066153]
julia> z = reshape(reinterpret(Float64, y), 2, :)
2×3 reshape(reinterpret(Float64, reinterpret(SArray{Tuple{2},Float64,1,2}, ::Array{Float64,2})), 2, 3) with eltype Float64:
0.0929609 0.827564 0.622823
0.314605 0.221642 0.066153
We can verify that x, y, and z all share their underlying data:
julia> x[1, 1] = 2
2
julia> y
1×3 reinterpret(SArray{Tuple{2},Float64,1,2}, ::Array{Float64,2}):
[2.0, 0.314605] [0.827564, 0.221642] [0.622823, 0.066153]
julia> z
2×3 reshape(reinterpret(Float64, reinterpret(SArray{Tuple{2},Float64,1,2}, ::Array{Float64,2})), 2, 3) with eltype Float64:
2.0 0.827564 0.622823
0.314605 0.221642 0.066153
Edit: actually, calling vec
is fine–it ensures that y is actually 1D, rather than being a 1xM matrix as in my code above. You can either do:
julia> y = reinterpret(SVector{2, Float64}, vec(x))
3-element reinterpret(SArray{Tuple{2},Float64,1,2}, ::Array{Float64,1}):
[5.0, 0.314605]
[0.827564, 0.221642]
[0.622823, 0.066153]
or:
julia> y = reshape(reinterpret(SVector{2, Float64}, x), :)
3-element reshape(reinterpret(SArray{Tuple{2},Float64,1,2}, ::Array{Float64,2}), 3) with eltype SArray{Tuple{2},Float64,1,2}:
[5.0, 0.314605]
[0.827564, 0.221642]
[0.622823, 0.066153]
1 Like