Reputation: 289
I want to understand how to be able to collect elements of n by m dimensional array and store them to n vectors of m dimensions. For example I have the following 3 x 2 array and I want to store the pair of each row into a vector.
Array1 = [ 1 0; 2 0; 3 0]
That gives:
3×2 Array{Int64,2}:
1 0
2 0
3 0
The idea is to make a for loop that in each iteration stores to a 2 dimensional vector the values of the array above.
I am not sure how to do it since the collect
function will only save elements of the same column from my experiments until now.
How can I store each pair into a vector then?
Upvotes: 3
Views: 1381
Reputation: 2332
It can be as simple as collect(eachrow(Array1))
julia> collect(eachrow(Array1))
3-element Vector{SubArray{Int64, 1, Matrix{Int64}, Tuple{Int64, Base.Slice{Base.OneTo{Int64}}}, true}}:
[1, 0]
[2, 0]
[3, 0]
This is short and which is, more importantly, type stable, so it is more performant than Any[]
solution. But it creates view
of the underlying Matrix
which sometimes is not what you want, especially taking into account that Julia is column-oriented, so row views are going to be relatively slow. If that is the case you can go with
julia> collect.(eachrow(Array1))
3-element Vector{Vector{Int64}}:
[1, 0]
[2, 0]
[3, 0]
which is still very fast.
But you may also consider your usage of this construction. If, for example, all you want is to iterate over rows, then there is no need to collect at all, you can use eachrow
straightforwardly without intermediate materialization.
Upvotes: 6
Reputation: 289
Ok, I found a satisfying answer I will post here for future reference.
First I define a list of vectors that can take any values:
listV = Any[];
Then I create a for
loop that stores each pair of elements of an array Array
using eachrow
:
for row in eachrow(Array);
push!(listV, row);
end
This is good enough.
Upvotes: 0