Reputation: 1896
Appart from allocating a new vector and filling its values one by one with the one of my matrix, how would I resize / refill a matrix of size n x m
to a vector of size n x m
generalizing the following example:
julia> example_matrix = [i+j for i in 1:3, j in 1:4]
3×4 Array{Int64,2}:
2 3 4 5
3 4 5 6
4 5 6 7
julia> res_vect = [2, 3, 4, 3, 4, 5, 4, 5, 6, 5, 6, 7]
12-element Array{Int64,1}:
2
3
4
3
4
5
4
5
6
5
6
7
An idea I had is:
res_vect = Int[]
for j in 1:size(example_matrix,2)
res_vect = vcat(res_vect, example_matrix[:,j])
end
I have the feeling it is not the optimal way yet I could not explain why...
Upvotes: 3
Views: 3886
Reputation: 42244
Julia allows you to do that sort of thing even without copying any data:
julia> m = [i+j for i in 1:3, j in 1:4]
3×4 Matrix{Int64}:
2 3 4 5
3 4 5 6
4 5 6 7
julia> m1 = vec(m) # m1 points to the same memory address as m
12-element Vector{Int64}:
2
3
4
3
4
5
4
5
6
5
6
7
julia> m2 = reshape(m, 4, 3) # m2 still points to the same memory address as m
4×3 Matrix{Int64}:
2 4 6
3 5 5
4 4 6
3 5 7
If you are wondering what "points to the same memory address" means have a look at this example:
julia> m2[1,1] = -66
-66
julia> m
3×4 Matrix{Int64}:
-66 3 4 5
3 4 5 6
4 5 6 7
Finally, if at any point you actually need a copy rather than a reference to the same data use copy(m)
or as commented by @DNF m[:]
(this is a dimension drop operator that returns a Vector
with copy of data from any Array
).
Upvotes: 7