Array Copies and Originals

Dear Community,

I’m wondering about the behaviour of Arrays. I’m trying to write code for one-hot-encoding and I stumbled about the follwing problem:


 i = [4,5];
 e = i.collect{|j|j.collect{0}};
 (2.collect{
 	var newEmpty = e.copy;
 	newEmpty.collect{|ls,index|
 	var indexForNewVal = 0.rrand(i[index]-1);
 	ls.put(indexForNewVal,1);};}; )
-> [ [ [ 1, 0, 1, 0 ], [ 1, 0, 0, 1, 0 ] ], [ [ 1, 0, 1, 0 ], [ 1, 0, 0, 1, 0 ] ] ]

Every nested slit should only contain a single “1”…
I would expect this code to create copies of the template “e” and not overwrite it.


 (2.collect{
 e.collectCopy{|ls,index|
	var indexForNewVal = 0.rrand(i[index]-1);
	ls.put(indexForNewVal,1);};}; )
 
 (2.collect{
 	var newEmpty = Array.newFrom(e);
 	newEmpty.collect{|ls,index|
 	var indexForNewVal = 0.rrand(i[index]-1);
 	ls.put(indexForNewVal,1);};}; )

actually do the same

How do I create real copy and not just another reference?
Thanks and all the best

Sem

Try using e.deepCopy instead

1 Like

of course… copy just makes a new array of the same pointers…

thanks!

1 Like