Copy vector?

#1

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?

0 Likes

#2

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
1 Like

#3

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

#4

Hi everyone,

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

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.

0 Likes

#5

Use deepcopy.

= is for assignment in Julia.

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

1 Like

#6

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
0 Likes