Reputation: 1
I've been stuck on this certain error for a while
# Define parameters for the walk
import numpy as np
import matplotlib.pyplot as plt
from itertools import cycle
colors = cycle('bgrcmykbgrcmykbgrcmykbgrcmyk')
dims = 3 # The number of dimensions
n_runs = 10 # amount of runs there are
step_n = 1000 # the number of steps
step_set = np.array([-1, 0, 1]) # the steps position
runs = np.arange(n_runs) # set the n_runs variable in order
origin = (step_n, dims) # setting the origin of the dimensions and steps position using the numpy module
#Plotting the path
fig = plt.figure(figsize=(10,10), dpi=250)
ax = fig.add_subplot(111, projection='3d') # axis level
ax.grid(False)
ax.xaxis.pane.fill = ax.yaxis.pane.fill = ax.zaxis.pane.fill = False
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
for i, col in zip(runs, colors):
# Simulating the steps in 3D
step_shape = np.random.randint(low=-10, high=10, size=(1,dims)) # creating a variable combining the number of steps with the number of dimensions and the size of each dimension
steps = np.random.choice(a=step_set, size=step_shape)
path = np.concatenate([origin, steps]).cumsum(0)
start = path[:1]
stop = path[-1:]
ax.scatter3D(path[:,0], path[:, 1], path[:,2],
c=col, alpha=0.25, s=1)
ax.plot3D(path[:,0], path[:,1], path[:,2],
c=col, alpha=0.5, lw=0.25)
ax.plot(start[:, 0], start[:, 1], start[:,2],
c=col, marker = '+')
ax.plot(stop[:, 0], stop[:, 1], stop[:,2],
c=col, marker ='o')
plt.title('3D Random Walk')
plt.savefig('random_walk_3d.png', dpi=250)
It hands me this error:
TypeError: only integer scalar arrays can be converted to a scalar index
Anybody know what's wrong here? I've looked through the code and searched for the error, but I can't really look for a specific error here. The line number is line number 30 according to the error, I will paste the line below:
steps = np.random.choice(a=step_set, size=step_shape)
Thanks for reading.
Upvotes: 0
Views: 106
Reputation: 21
Your error is due to the size of the array step_shape that you are using. If you check: https://numpy.org/doc/stable/reference/random/generated/numpy.random.choice.html you can see that the argument needs to be an int or tuple of ints. If you print the variable that you are using you get something like:
[[-8 8 7]]
which is indeed a of size (1,3) while it needs to be a 1-dimensional array. So you need to change line 29 of your code to:
step_shape = np.random.randint(low=-10, high=10, size=(dims))
Note also that you need to pass positive integers to the size argument of the function (be sure to check the reference to understand what the size argument is doing).
If you fix this there is still a dimension error in your line:
path = np.concatenate([origin, steps]).cumsum(0)
Upvotes: 1