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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With