Copy vector?

I just realized this behavior:

julia> x = [ 0. , 0. ]
2-element Array{Float64,1}:
 0.0
 0.0

julia> y = x
2-element Array{Float64,1}:
 0.0
 0.0

julia> y[1] = 1.
1.0

julia> x
2-element Array{Float64,1}:
 1.0
 0.0

x and y are just different names for the same vector. How do I copy a vector into another one, then?

Also, is there any style suggestion to avoid running into errors given that we could be modifying previous values of array variables this way?

you can (should?) use copy

julia> x = [0., 0.];
julia> y = copy(x);
julia> y[1] = 1.;
julia> x
2-element Array{Float64,1}:
 0.0
 0.0
2 Likes

Try copy or deepcopy, should do it. This is an intrinsic feature of the language; it is not a problem as long as one is aware of it.

1 Like

Hi everyone,

I’m quite new to Julia and quite recently realized the same issue pointed out by @lmiq.

To sum up, as a general suggestion, would you recommend always using copy if interested in, e.g., y = copy(x), such that from this line of code onward I would like x and y to be absolutely independent?

As a side note, I would ask in which cases it could be useful to use =.

Thanks in advance.

Use deepcopy.

= is for assignment in Julia.

(Also, please don’t resurrect old topics).

1 Like

There are a few algorithms where one wants to “swap” two vectors.
Instead of copying them over, one could just switch the names:

x, y = y, x
1 Like