Reputation: 707
I am trying to code a random path with several trajectories. My code is below and calculates a path, but the for loop does not create multiple different paths. Rather, it plots the same path n times on top of itself. I want to be a able to graph n number of different paths from within the same for loop, store the values in a single array, then graph them next to each other. Any idea what I am doing wrong?
from numpy.random import randint
n = 1000
moves = randint(0, 2, size=n)
y = 0
x = [y]
n2 = 5
for t in range(n2):
for i in moves:
if i == 1:
y = y + 1
if i == 0:
y = y - 1
x.append(y)
plt.plot(x)
y = 0
x = [y]
Upvotes: 0
Views: 977
Reputation: 59731
If you want to create a different path on each iteration of the loop then you should call randint
inside of the loop, and calculate the path there
from numpy.random import randint
n = 1000
n2 = 5
for t in range(n2):
moves = randint(0, 2, size=n)
y = 0
x = [y]
for i in moves:
if i == 1:
y = y + 1
if i == 0:
y = y - 1
x.append(y)
plt.plot(x)
y = 0
x = [y]
If you want to store all the computed paths, you can store them in a list or array:
from numpy.random import randint
n = 1000
n2 = 5
paths = [] # use something like numpy.empty((n2, n)) to use an array
for t in range(n2):
moves = randint(0, 2, size=n)
y = 0
x = [y]
for i in moves:
if i == 1:
y = y + 1
if i == 0:
y = y - 1
x.append(y)
paths.append(x) # use something like paths[t] = x with an array
plt.plot(x)
y = 0
x = [y]
Then paths[i]
would contain the i-th computed path, and paths[i][j]
(or paths[i, j]
with an array) the j-th position of the i-th path.
Yet another alternative would be to store all the paths in a linear list (or a one-dimensional array) one after the other, so paths[:n]
would be the first path, then paths[n:2*n]
, paths[2*n:3*n]
, etc.
Upvotes: 2