Maybe I do not understand how Table works, but I find this very confusing and it took me a long time to debug because this was part of a much more complicated routine.
I am trying to build an array that keeps changing within a table with two indices (here a simpler case with a single index is shown)
RandomSeed[3];
init = ConstantArray[0, 4];
final = Block[{inter = init}, Table[
Echo[inter];
Echo[{index}];
inter[[index]] = RandomChoice[{-2, -1, 1, 2}], {index,
Reverse@Range[4]}]];
final
Like the code snippet above. The key thing is that the index does not start from the usual way of counting up by Range[4], but here it is the reverse order.
When I echo I see that the intermediate (inter) array is being filled up in the correct order: The first random choice fills up the 4th entry of the array. But when the calculation finishes and I print final, I see that final array has the reverse order, its first element is the first operation done in the Table, namely the 4th entry of the array when seen from inside.
I find this very strange: If I would like to place an entry to the 4th position of an array, why would leaving the Table change this?
In this case it can easily be converted to the order I like by a simple Reverse but I would like to consider cases where Reverse@Range[4] is replaced by RandomSample@Range[4] where I don't want to do this correction because I don't care to know what RandomSample is taken in different iterations.
Maybe I have a big misunderstanding of how Table is supposed to operate but I figure this may be of general relevance.
final
is being filled with the last value of the argument to theTable
, i.e.inter[[index]]
with the index values{4,3,2,1}
so theTable
is built{index[[4]], index[[3]], index[[2]], index[[1]]}
. Sofinal
is the reverse ofindex
$\endgroup$final
. You apparently wantinter
; so useRandomSeed[3]; inter = ConstantArray[0, 4]; Table[inter[[index]] = RandomChoice[{-2, -1, 1, 2}], {index, Reverse@Range[4]}]; inter
$\endgroup$