我正在尝试为某些BOID对象构建一个模拟器,但我在使用matplotlib的动画模块时遇到了一些麻烦(没有得到非常钝的文档的帮助)。 这是代码:
from mpl_toolkits.mplot3d import Axes3D #Import axes
import matplotlib.pyplot as plt #Import plotting library
from matplotlib import animation
import numpy as np #Import numpy library
dim = 2 #Defines the dimensionality of the system
n = 6 #Number of BOIDS
tmax = 5 #Length of sim
o = np.zeros(dim) #Origin as vector
r = np.random.rand(n,dim) #Places BOIDs randomly with co-ordinates (x,y,z) from 0 to 1. Has dimensions n and dim
v = 2*np.random.rand(n,dim)-1#Sets initial velocity of each BOID from -1 to 1 in each cardinal direction
rt = np.zeros((tmax,n,dim)) #This array contains the whole system's positions at each point in time
x = np.empty(n)
y = np.empty(n)
"""rt[a]is r at t=a
rt[a][b] is r array for t=a and n=b
rt[0][a][b] is the x co-ordinate of boid n=b at t=a"""
fig = plt.figure() #Setting up a plotting figure for animation
ax = fig.add_subplot(111) #Establishes a subplot with axes
ax.grid(True,linestyle='-',color='0.75') #Sets up a grid on subplot
ax.set_xlim(-50,50)
ax.set_ylim(-50,50) #Set limits for x and y axes
for t in range (0,tmax):
for i in range (0,n):
r[i] = r[i] + v[i]
rt[t][i] = r[i]
def init():
for i in range (0,n):
x[i] = rt[0][0][i]
y[i] = rt[1][0][i]
print(i)
return x,y,
def update(j):
for i in range (0,n):
x[i] = rt[0][j][i]
y[i] = rt[1][j][i]
return x,y
anim = animation.FuncAnimation(fig, update, frames=tmax, init_func=init, interval=20, blit=True)
我的问题是双重的;目前代码给了我这个错误:
x[i] = rt[0][0][i]
IndexError: index 2 is out of bounds for axis 0 with size 2
建议我两个数组元素的尺寸不匹配,但它们应该只是一个数字而不是一个数组,所以我不明白什么是错的。
另外,我真的不了解函数init和update的必要性。我不能简单地为rt片制作动画片吗?
提前致谢。