Stream: helpdesk (published)

Topic: Converting Vector of Vectors to Vec of SVectors


view this post on Zulip Davi Sales Barreira (Sep 26 2023 at 20:24):

Friends, I'm trying to convert vectors such as [[1,2],[1,2]] to a vector of static arrays. If I do SVector([[1,2],[0,0]]...) it works, but not for the case of [[1,2]]. How to circumvent this case? The vectors inside always have size 2.

view this post on Zulip Daniel González (Sep 26 2023 at 20:26):

If you know the eltype beforehand, this seems to work for me:

julia> Vector{SVector{2, Int64}}([[1,2], [1,2]])
2-element Vector{SVector{2, Int64}}:
 [1, 2]
 [1, 2]

julia> Vector{SVector{2, Int64}}([[1,2]])
1-element Vector{SVector{2, Int64}}:
 [1, 2]

view this post on Zulip Daniel González (Sep 26 2023 at 20:30):

otherwise I guess you can intercept the eltype with a function

julia> function svector2ify(v::Vector{Vector{T}}) where {T}
           Vector{SVector{2, T}}(v)
       end

julia> svector2ify([[1,2], [1,2]])
2-element Vector{SVector{2, Int64}}:
 [1, 2]
 [1, 2]

julia> svector2ify([['a', 'b']])
1-element Vector{SVector{2, Char}}:
 ['a', 'b']

view this post on Zulip Davi Sales Barreira (Sep 26 2023 at 20:32):

Thanks!

view this post on Zulip Leandro Martínez (Sep 27 2023 at 00:07):

julia> SVector{2}.([[1,2],[3,4]])
2-element Vector{SVector{2, Int64}}:
 [1, 2]
 [3, 4]

All the option create new vectors, you cannot "convert", because the layouts are different.


Last updated: Dec 28 2024 at 04:38 UTC