I’m using solve_ivp in python to solve a set of differential equations in state-space form.My code is as follows:
JavaScript
x
21
21
1
import numpy as np
2
import matplotlib.pyplot as plt
3
from numpy import zeros
4
from scipy.integrate import solve_ivp
5
vin=12;
6
vdon=.7;
7
X=np.array([[0],[0],[0],[0]])
8
U= np.array([[vin],[vdon]]);
9
A1=np.array([[(-.01-10)/1e-5,-1/1e-5,10/1e-5,0] ,[1/1e-8,-1/(.05*1e-8),0,0],[10/1e-8,0,(-10-1)/1e-8,-1/1e-8],[0,0,1/1e-3,0]]);
10
B1=np.array([[1/1e-5,0],[0,1/(.05*1e-8)],[0,0],[0,0]]);
11
def conv(t,X):
12
xdot= A1.dot(X).reshape(4,1)+B1.dot(U)
13
return np.squeeze(np.asarray(xdot))
14
tspan=[0,.001]
15
16
X0=np.array([0,0,0,0])
17
sol=solve_ivp(conv,tspan,X0)
18
t=np.linspace(0,.001,10000)
19
tend=.001
20
plt.plot(t,X)
21
It shows error while using the normal plt.plot(t,X)
command.
How do I plot the graph between X
and t
?
Please help
Advertisement
Answer
It’s a bit unclear what’s being calculated here, but checking solve_ivp
‘s documentation, it seems the return value (sol
in this case) has a number of fields. sol.t
is the list of time points. sol.y
are the calculated values for each of the 4 components of X
, corresponding to each value of sol.t
.
Here is a way to plot each of the 4 components (they all start at 0 because X0=(0,0,0,0)
). The interpretation depends on the exact problem being solved.
JavaScript
1
32
32
1
import numpy as np
2
import matplotlib.pyplot as plt
3
from numpy import zeros
4
from scipy.integrate import solve_ivp
5
6
vin = 12
7
vdon = .7
8
X = np.array([[0], [0], [0], [0]])
9
U = np.array([[vin], [vdon]])
10
A1 = np.array([[(-.01 - 10) / 1e-5, -1 / 1e-5, 10 / 1e-5, 0],
11
[1 / 1e-8, -1 / (.05 * 1e-8), 0, 0],
12
[10 / 1e-8, 0, (-10 - 1) / 1e-8, -1 / 1e-8],
13
[0, 0, 1 / 1e-3, 0]])
14
B1 = np.array([[1 / 1e-5, 0],
15
[0, 1 / (.05 * 1e-8)],
16
[0, 0],
17
[0, 0]])
18
19
def conv(t, X):
20
xdot = A1.dot(X).reshape(4, 1) + B1.dot(U)
21
return np.squeeze(np.asarray(xdot))
22
23
tspan = [0, .001]
24
25
X0 = np.array([0, 0, 0, 0])
26
sol = solve_ivp(conv, tspan, X0)
27
for i in range(sol.y.shape[0]):
28
plt.plot(sol.t, sol.y[i], label=f'$X_{i}(t)$')
29
plt.xlabel('$t$') # the horizontal axis represents the time
30
plt.legend() # show how the colors correspond to the components of X
31
plt.show()
32