Search code examples
pythonarraysloopsfor-looprandom-walk

Python for loop only saves the last loop in my 2-d array


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?


Solution

  • You've, for some reason, chosen to execute

    y = zeros((10000, 5))
    

    over and over again, each time through the outer loop.

    As an obvious consequence, only the last assignment to y can possibly "take", evidently overriding any previous assignment to the same name. What other behavior could you possibly expect from such repeated assignments?!

    Move this assignment outside the outer loop, and there will be no "overriding" of the name y.