1

Here is the example code. I can't understand why the first element in array B also be revised. Can I keep the same element in array B?

julia> A = [0.0 0.1 0.2 0.3];

julia> B = A;

julia> A[1] = 0.1;

julia> A
1×4 Array{Float64,2}:
 0.1  0.1  0.2  0.3

julia> B
1×4 Array{Float64,2}:
 0.1  0.1  0.2  0.3
Nan
  • 39
  • 4
  • Another possible duplicate, probably a better one: https://stackoverflow.com/q/35115414/1233251 `B = A` is a variable assignment, both variables will be bound to the same array. You can use `copy` to create a new array for the variable `B`. – E_net4 Mar 10 '19 at 00:18

1 Answers1

3

Julia Array is passed by reference. You need to create a copy:

julia> A = [0.0 0.1 0.2 0.3];

julia> B = deepcopy(A)
1×4 Array{Float64,2}:
 0.0  0.1  0.2  0.3

julia> A[1] = 0.1;

julia> A, B
([0.1 0.1 0.2 0.3], [0.0 0.1 0.2 0.3])

Note that for this code just copy will be also enough but if for example you have an Array of objects that you mutate deepcopy should be used.

Przemyslaw Szufel
  • 40,002
  • 3
  • 32
  • 62