Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning a value to an element of a tuple in Julia

Tags:

tuples

julia

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)

like image 607
Nikhil Anand Avatar asked Oct 27 '25 15:10

Nikhil Anand


2 Answers

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

like image 151
Alexander Morley Avatar answered Oct 29 '25 05:10

Alexander Morley


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.

like image 35
Chris Rackauckas Avatar answered Oct 29 '25 05:10

Chris Rackauckas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!