user1438310
user1438310

Reputation: 787

Assignment to multidimensional array in julia

The following simple piece of code returns, what seems to me, an unexpected result:

srand(101)

# create a multidimensional array that will house 3 matrices of dimensions 2x2
A = Array(Array{Float64,2},3)

# initialise array with zero matrices (is this the culprit?)
fill!(A, zeros(2,2))

# populate array (some dummy computation to illustrate my problem)
for ii=1:2
   for jj=1:2
      aux = randn(1,3)
      for dd=1:3
         A[dd][ii,jj]=aux[dd]
      end
   end
end

When I run the above code, my array A reads:

3-element Array{Array{Float64,2},1}:
 2x2 Array{Float64,2}:
  1.2821   -2.10146
 -1.00158   1.8163 
 2x2 Array{Float64,2}:
  1.2821   -2.10146
 -1.00158   1.8163 
 2x2 Array{Float64,2}:
  1.2821   -2.10146
 -1.00158   1.8163 

Why are the the three 2x2 matrices identical when I am actually creating them randomly?

I do understand that one has to be careful when assigning arrays to arrays in Julia, but somehow the error eludes me.

The funny thing I discovered is that if I initialise A like follows:

for dd=1:3
   A[dd] = zeros(2,2)
end

as opposed to with

fill!(A, zeros(2,2))

like above, then I get what I consider the correct result:

3-element Array{Array{Float64,2},1}:
2x2 Array{Float64,2}:
-0.176283   0.22073 
-1.71021   -0.575144
2x2 Array{Float64,2}:
1.94395   1.09946 
1.65326  -0.446783    
2x2 Array{Float64,2}:
1.2821   -2.10146
-1.00158   1.8163

Note that the last matrix is the matrix that is repeating above.

Is it the array initialisation that is wrong, or the assignment? I guess it is the combination of the two, depending on how exactly you do them. Thanks in advance.

Upvotes: 3

Views: 927

Answers (1)

Moritz Schauer
Moritz Schauer

Reputation: 1417

You almost answered it yourself. Yes,

fill!(A, zeros(2,2))

is the culprit, after the command each cell of A contains the same array (is connected to the same 2x2 spot in memory). The function zeros gets called once.

Filling the cells of the array in a loop

for dd=1:3
   A[dd] = zeros(2,2)
end

calls the function zeros 3 times, returning a different zero array for each cell (located at different positions in memory).

Upvotes: 6

Related Questions