我是这个论坛的新手,
我有下一个代码,我需要的是能够从数组中提取每个元素并将其绘制出来,但是我对如何做到这一点感到困惑。 我了解部分原因是我只得到数组的末尾,因为for循环当然会返回该最终值。
from numpy import linspace, zeros, asarray
import matplotlib.pyplot as plt
import numpy as np
def ode_EULER(f, C_i, dt, T):
N_t = int(round(float(T)/dt)) #calculate number of iterations n+1
f_ = lambda x, t: asarray(f(x, t)) #ensure that the list of equations are transform into array
x = zeros((N_t+1, len(C_i))) #init array full with zeros [0. 0.]
t = linspace(0, N_t*dt, len(x)) #start from 0 to 100 with len(x) number of samples
x[0] = C_i #pass the inital conditions to the first array element
for n in range(N_t): #start computations
x[n+1] = x[n] + dt*f_(x[n], t[n])
return x, t
## solve ODe
# # z = odeint(model,z0,t)
def insystem(): #the system to be solved
def f(x, x2):
X1, X2 = x #define both equations in one X (as vector)
return [X2, X1-X2+2*((0.5)*((X2-X1)-(X2)-np.sign(X1-2)))] #[X2, X1-X2+2*(u)]
#parameters
dt = 0.01 #precision
T = 20 # Simulation time
C_i = np.array([[0, 0],[1, 1],[2, 2],[3, 3]])
nooics=len(C_i)
for i in range(0,nooics):
x_old, t_old = ode_EULER(f, C_i[i], dt, T)
X1_old = x_old[:,0]
X2_old = x_old[:,1]
plt.plot(t_old, X1_old, 'b-',\
t_old, X2_old, 'r-')
plt.xlabel('time');
plt.ylabel('S (blue), I (red)')
plt.show()
if __name__ == '__main__':
insystem()