23

I have an Array d that contains an Array of floats:

julia> d
99-element Array{Array{Float64,1},1}:
...

I'm trying to convert it into a 2-dimensional Array, and I sucessfully achieved my goal with:

data = Array(Float64,length(d),length(d[1]))
for i in 1:length(d)
    for j in 1:length(d[1])
        data[i,j] = d[i][j]
    end
end

Is there a simpler way of doing this?

prcastro
  • 2,178
  • 3
  • 19
  • 21

2 Answers2

34

hcat(d...) and vcat(d...) should do what you want.

ivarne
  • 3,753
  • 1
  • 27
  • 31
  • @scry Can you elaborate? The question is about converting a 1d array of 1d arrays to a 2d array. The prescribed method works. – ivarne Feb 15 '15 at 19:38
  • 10
    I just want to note that the `...` is significant here, it will [splat](http://docs.julialang.org/en/release-0.3/manual/faq/#what-does-the-operator-do) the arguments to the function (thank you @MattB). I wrote (and deleted) a misleading answer because I didn't know they were to be used literally. – scry Feb 15 '15 at 21:41
  • 4
    Also, to get a matrix in the same shape, take the transpose of the result of hcat: `hcat(d...)'` – scry Feb 15 '15 at 21:46
  • Or just use ``vcat(d...)`` instead. – ivarne Feb 16 '15 at 03:23
  • 8
    `vcat` gives me a "flattened" one-dimensional array - unless I'm missing something, it's not equivalent. – scry Feb 16 '15 at 06:00
  • Oops! Sorry! Definitely my mistake. – ivarne Feb 16 '15 at 17:38
6

If your array of array is supposed to represent a matrix and you want to preserve the logic, then this is the simpler I found (julia 1.1)

julia> a=[ [1,2], [3,4], [5,6] ]
3-element Array{Array{Int64,1},1}:
 [1, 2]
 [3, 4]
 [5, 6]

julia> permutedims(reshape(hcat(a...), (length(a[1]), length(a))))
3×2 Array{Int64,2}:
 1  2
 3  4
 5  6

One could use transpose instead of permutedims.

Chickpioupiou
  • 61
  • 1
  • 1