Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to flatten a 2D array in julia?

Tags:

julia

Is there a function in julia which converts a 2D array to a 1D array? For example I know how to do it by defining a function, but I don't want to write it every time.

function flatten(Mat)
n, m = size(Mat)
flattened = zeros(m*n)
for i=1:n
    for j=1:m
        flattened[(i-1)*m + j] = Mat[i,j]
    end
end
return flattened
end
like image 613
bitWise Avatar asked Dec 14 '22 10:12

bitWise


1 Answers

You can use vec (https://docs.julialang.org/en/v1/base/arrays/#Base.vec):

julia> A = rand(2, 2)                                                     
2×2 Array{Float64,2}:
 0.843062  0.164179
 0.167501  0.800111

julia> vec(A)                                                             
4-element Array{Float64,1}:
 0.8430624537022231 
 0.16750120450998196
 0.16417911360611237
 0.8001111380491013
like image 141
fredrikekre Avatar answered Dec 27 '22 13:12

fredrikekre