Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
418 views
in Technique[技术] by (71.8m points)

arrays - Julia - Transform a matrix to a vector

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...

question from:https://stackoverflow.com/questions/65890158/julia-transform-a-matrix-to-a-vector

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...