I am producing one dimensional random walks and I want my for loop to save the maximum distance from the origin that has been reached so far, as time progresses. 5 random walks are produced. This is my code:
for j in range(5):
r = rand(10000)
t = range(10000)
x = zeros(10000)
y = zeros((10000, 5))
for i in range(10000):
walk = r[i]
if walk < 0.5:
x[i] = x[i-1] - 1
y[:,j]= maximum.accumulate(abs(x))
else:
x[i] = x[i-1] + 1
y[:,j]= maximum.accumulate(abs(x))
plot(t,x, label="Walk %d" %(j+1))
title("1-D Random Walk (Position versus Time)")
xlabel("Time")
ylabel("Position")
legend(loc="best")
grid()
The problem is that after the for loop iterates over the set range (5) the output 2-d array only includes the last iteration. Somehow, it overwhites the previous ones, so I would only get a 10000x5 array with only the last row filled in.
How can I make this work?