Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialize an array of arrays in Julia

Tags:

julia

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).

like image 704
fhucho Avatar asked Dec 05 '13 21:12

fhucho


People also ask

How do you create an array of arrays in Julia?

Here, you can give any value for 'dims' and an array of that dimension will be created. An Array in Julia can be created with the use of a pre-defined keyword Array() or by simply writing array elements within square brackets([]). There are different ways of creating different types of arrays.

How do you initialize an empty array in Julia?

To initialize an empty array, it is perfectly valid to use n = 0 in the above expressions. A possible source of errors would be to confuse this array with an empty array of “Any” type, which is initialized as follows: v = [] # Same as Any[], and you can't change this type easily later (gotcha!)

How do you initialize a vector in Julia?

The easiest way to initialize them are probably list comprehensions, for example: julia> [[Vector{Float64}(undef, 4) for _ = 1:5] for _ = 1:6] 5-element Array{Array{Array{Float64,1},1},1}: ...

How do you make an array of zeros in Julia?

This is usually called with the syntax Type[] . Element values can be specified using Type[a,b,c,...] . zeros([T=Float64,] dims::Tuple) zeros([T=Float64,] dims...) Create an Array , with element type T , of all zeros with size specified by dims .


2 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.

like image 140
Sean Mackesey Avatar answered Sep 24 '22 13:09

Sean Mackesey


Sean Mackesey's answer will give you something of type Array{Array{T,N},1} (or Array{Array{Int64,N},1}, if you put the type in front of []). If you instead want something more strongly typed, for example a vector of vectors of Int (i.e. Array{Array{Int64,1},1}), use the following:

a = Vector{Int}[ [1,2], [3,4] ] 
like image 33
Jim Garrison Avatar answered Sep 23 '22 13:09

Jim Garrison