I am facing a problem with tuples in Julia. Here is what I am trying to do
julia> temp = [1 2 3]
julia> A = tuple(temp, temp)
julia> B = tuple(A,A,A)
B looks like this :
julia> B
((
[1 2 3],
[1 2 3]),(
[1 2 3],
[1 2 3]),(
[1 2 3],
[1 2 3]))
I understand I can access the 'very' first element in B by B[1][1][1] which returns 1 (as expected)
But, if I try to assign a particular value to B[1][1][1], say if I do,
julia> B[1][1][1] = 20, this is what I get,
julia> B
((
[20 2 3],
[20 2 3]),(
[20 2 3],
[20 2 3]),(
[20 2 3],
[20 2 3]))
The first elements of all the sub-tuples have been changed. Is there a way to change the value of B[1][1][1] without affecting the other sub-tuples ??
Thanks in advance.
PS : I'm using Julia 0.5.0 on Ubuntu 16.04 (64-bit)
This is not quite a problem with tuples. Exactly the same thing will happen if you use arrays.
A = (temp, temp) will reference the same address in memory twice. So you need to do A = (copy(temp), copy(temp))
But ...
copy(x)
Create a shallow copy of x: the outer structure is copied, but not all internal values. For example, copying an array produces a new array with identically-same elements as the original.
So for B = (A, A, A) we need to use deepcopy in order to get the values (rather than the references) of each variable. i.e. B = (deepcopy(A), deep copy(A), deepcopy(A))
Check out the docs for copy and deepcopy here:
http://docs.julialang.org/en/release-0.4/stdlib/base/#Base.copy
A = tuple(temp, temp)
You make this a tuple of all the same arrays (note you can just write A = (temp,temp)). If you want to use a copy of the array, use A = (copy(temp),copy(temp)). The value of an array is its reference, and thus when you do A = (temp,temp), you just have two references to the same slab of memory, which is why when you change one, the other changes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With