A function that takes a 2D array and returns a tuple of array columns?

How to convert a 2D array ( n-by- m) to a tuple mof length vectors ncorresponding to the columns of the array? In other words, I need a function fsuch that

julia> f([1 2 3; 4 5 6])
([1,2,3],[4,5,6])

Does Julia provide such a function? If not, how can I write one?

+4
source share
1 answer

As far as I know, there is no built-in Julia function that does what you want, i.e.

  • take a two-dimensional array ( Array{T,2}),
  • returns a tuple of vectors (Array{T,1},Array{T,1},...)) corresponding to the columns of the array.

,

  • ,
  • ...,
  • size,
  • tuple.

function f{T<:Any}(A::Array{T,2})
    return tuple([A[:,c] for c in 1:size(A,2)]...)
end

julia> A = rand(4,5)
4x5 Array{Float64,2}:
 0.21149   0.841894  0.275182   0.33981   0.0142366
 0.88409   0.718435  0.368415   0.521676  0.527016 
 0.482613  0.211109  0.394439   0.141225  0.071393 
 0.4477    0.330136  0.0303556  0.610213  0.699511 

julia> tup = f(A)
([0.21149,0.88409,0.482613,0.4477],[0.841894,0.718435,0.211109,0.330136],[0.275182,0.368415,0.394439,0.0303556],[0.33981,0.521676,0.141225,0.610213],[0.0142366,0.527016,0.071393,0.699511])

julia> typeof(tup)
(Array{Float64,1},Array{Float64,1},Array{Float64,1},Array{Float64,1},Array{Float64,1})
+4

Source: https://habr.com/ru/post/1569195/


All Articles