Hi all,
I've had a problem with some explicit finite-difference code, and after
playing with it I've traced the error back to the following
counter-intuitive behavior.
In this little loop, I create a vector 'a', and progressively add 1 to its
values, each time storing the altered vector in a growing array, astore:
astore = []
a = [1,2]
for j = 1:5
a = a + 1
push!(astore,a);
println(astore)
end
This works as expected. However, when I slightly modify the code, replacing
'a = a + 1' by a loop over all the elements of a:
astore = []
a = [1,2]
for j = 1:5
for i = 1:2
a[i] = a[i] + 1
end
push!(astore,a);
println(astore)
end
I get a completely different result! In this code, the new value of 'a'
over-writes all the previously stored values in 'astore'. Running both in
the REPL will immediately reveal the difference.
My question is, what's going on here? Is this expected behavior? Why would
these different approaches, using a vectorised form or a loop, give
different results? And if this is expected behavior, can you recommend a
better way of storing the 'a' values in code of the second type above,
which doesn't over-write previously stored results.
Thanks
Tom