Pascal Romon
Pascal Romon

Reputation: 13

creating 2 dimensional array of unspecified (varying) size

Newbie question: I want to dynamically create an integer 2D array M[i,j], whose sizes (in both dimensions) are unknown beforehand. Moreover, for each index i, the size of the i-th row may vary.

Question 1: How do I declare such an array (do I even have to)? I have tried Array[], Array(Int64,1...), and Array((Int,Int),0)as in this hint and others.

Question 2: once created, how to I populate the array in a smart and concise way? Say my i-th row is suppose to be equal to a given 1-dimensional B, I would like to write

A[i] = B

or

A[i,:] = B

or even

A[i,1:n] = B

where n is the size of B. All of these give me a BoundsError(). Slicemight do the trick, but I cannot make it agree with my declaration.

Upvotes: 1

Views: 3532

Answers (1)

tholy
tholy

Reputation: 12179

You don't want a 2D array here, because in a 2D array all rows are of the same size. Instead, you want a vector-of-vectors. For example:

A = Array(Vector{Int}, 5)
A[1] = rand(1:10, 3)
A[2] = rand(1:100, 22)

If you inspect A, you'll see something like this:

julia> A
5-element Array{Array{Int64,1},1}:
    [5,7,7]                                                        
    [1,63,40,86,61,39,98,5,68,97  …  78,49,44,89,48,63,90,90,86,83]
 #undef                                                            
 #undef                                                            
 #undef

Another great tool is to use a comprehension:

julia> A = Vector{Int}[ [1:m] for m = 1:5]
5-element Array{Array{Int64,1},1}:
 [1]        
 [1,2]      
 [1,2,3]    
 [1,2,3,4]  
 [1,2,3,4,5]

The main thing you'll want to be careful about is that each element of A is a reference to a vector; if you assign

A[1] = b
A[2] = b

then any change to b will affect both A[1] and A[2]. If you don't want that, use

A[1] = copy(b)
A[2] = copy(b)

Upvotes: 5

Related Questions