Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Julia transpose vector of vectors

I have a vector of vectors, say

julia> m = [[1,2],[3,4],[5,6]]
3-element Vector{Vector{Int64}}:
 [1, 2]
 [3, 4]
 [5, 6]

which I want to transpose, meaning that I want a 2-element vector with the corresponding 3-element vectors (1,3,5 and 2,4,6).

This could obviously be done with loops, but I suspect that this is slow and am sure that Julia has a better solution for it. The best one I could come up with so far looks like that:

julia> matrixM = reshape(collect(Iterators.flatten(m)), (size(m[1],1),size(m,1)))
2×3 Matrix{Int64}:
 1  3  5
 2  4  6

julia> map(i->matrixM[i,:], 1:size(matrixM,1))
2-element Vector{Vector{Int64}}:
 [1, 3, 5]
 [2, 4, 6]
like image 842
MetaColon Avatar asked Oct 19 '25 16:10

MetaColon


1 Answers

You can use:

julia> using SplitApplyCombine

julia> invert([[1,2],[3,4],[5,6]])
2-element Vector{Vector{Int64}}:
 [1, 3, 5]
 [2, 4, 6]
like image 88
Bogumił Kamiński Avatar answered Oct 21 '25 08:10

Bogumił Kamiński



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!