I try to simulate a LTI system using Python. The structure is xDot = Ax. I defined the system dynamics as a function I then call using solve_ivp
. Calling the function itself works, but simulating the system results in the following error
ValueError: matmul: Input operand 1 does not have enough dimensions (has 0, gufunc core with signature (n?,k),(k,m?)->(n?,m?) requires 1)
for the line with the matrix multiplication in the system dynamics definition. Below is the code.
import numpy as np
from scipy import integrate
import matplotlib.pyplot as plt
# System Parameters
l = 1 # Pendulum length
g = 9.81 # gravity
# Initial Conditions
x0 = np.array([np.pi/2, 0])
# Simulation parameters
tStart = 0
tEnd = 4
t_span = [tStart, tEnd]
t = np.linspace(tStart,tEnd,10) # Simulation time
# System matrices
A = np.array([[0, 1],[-g/l, 0]])
def dynamics(x, t):
xdot = -A@x
return xdot
y = integrate.solve_ivp(dynamics, t_span, x0)
How do I need to adjust the system definition to make this work?
CodePudding user response:
According to the docs the signature of the dynamics should be dynamics(t, x)
with the scalar t
as the first argument. This is how scipy.integrate.solve_ivp
calls the given dynamics.
In your case, the error is caused by the fact that the matrix A
is multiplied with the scalar t
and the error message Input operand 1 does not have enough dimensions
indicates that the matrix multiplication goes wrong.
The solution therefore is to switch the arguments to dynamics(t, x)
. Inside dynamics
you can ignore the parameter t
as long as your matrix A
is not time-dependent.