Wrong order in push! operator

Hi,
I have a problem using the push! operator. It seems that it does not push the next elements at the end of the arrays. Can someone confirm my result:

using Distributions

e = 1 * 10^(-2)
n_data = 2

x = rand(Uniform(-e, e), n_data, 1)
y = rand(Uniform(-e, e), n_data, 1)
z = rand(Uniform(-e, e), n_data, 1)

vec1 = []
vec2 = []

for xi in x
 a = zeros(3)
 a[1] = xi
 for yi in y
     a[2] = yi
     for zi in z
         a[3] = zi
         b = 2 * a
         push!(vec1, a)
         push!(vec2, b)

     end
 end
end

println(vec1[1])
println(vec2[1])

The output I get is :

[-0.007628929670578818, -0.007324861395442884, 0.003913249936206481]
[-0.015257859341157635, -0.015167500156704537, -0.014534791007813352]

which is not corresponding with b = 2*a.

The problem is that the vector a is mutated in the two inner loops (only the outermost loop creates a new vector every time). Consider the following example:

julia> v = [];

julia> a = [1,2,3];

julia> push!(v, a)
1-element Array{Any,1}:
 [1, 2, 3]

julia> a[3] = 100
100

julia> push!(v, a)
2-element Array{Any,1}:
 [1, 2, 100]
 [1, 2, 100]
3 Likes

See this post on push!

2 Likes