Initialize an array of arrays in Julia

Viewed 23731

I'm trying to create an array of two arrays. However, a = [[1, 2], [3, 4]] doesn't do that, it actually concats the arrays. This is true in Julia: [[1, 2], [3, 4]] == [1, 2, 3, 4]. Any idea?

As a temporary workaround, I use push!(push!(Array{Int, 1}[], a), b).

7 Answers

If you want an array of arrays as opposed to a matrix (i.e. 2-dimensional Array):

a = Array[ [1,2], [3,4] ]

You can parameterize (specify the type of the elements) an Array literal by putting the type in front of the []. So here we are parameterizing the Array literal with the Array type. This changes the interpretation of brackets inside the literal declaration.

For those wondering, in v0.7 this is rather similar:

Array{Array{Float64,1},2}(undef, 10,10)  #creates a two-dimensional array, ten rows and ten columns where each element is an array of type Float64

Array{Array{Float64, 2},1}(undef,10) #creates a one-dimensional array of length ten, where each element is a two-dimensional array of type Float64

You probably want a matrix:

julia> a = [1 2; 3 4]
2x2 Int64 Array:
 1  2
 3  4

Maybe a tuple:

julia> a = ([1,2],[3,4,5])
([1,2],[3,4,5])
Related