我想通过Python控制我的simulink模型。我的 simulink 模型如下图所示。我的 simulink 模型的名称为“ToyExample_V2”
我想将“1”作为常量块的输入值,并且我想以时间步长值 0.1 运行模拟 10 秒。
为了完成此任务,我编写了以下代码。
import matlab.engine
class SimulinkPlant:
def __init__(self, modelName='ToyExample_V2'):
self.modelName = modelName
self.eng = None
def setControlAction(self, Input):
# Set the input value in the Simulink model
self.eng.set_param('{}/Input'.format(self.modelName), 'value', str(Input), nargout=0)
def connectToMatlab(self):
print("Starting Matlab")
self.eng = matlab.engine.start_matlab()
print("Connected to Matlab")
# Load the model
self.eng.eval("model = '{}'".format(self.modelName), nargout=0)
self.eng.eval("load_system(model)", nargout=0)
# Set the input value to 2 in the Simulink model
self.setControlAction(1)
print("Initialized Model")
# Set the simulation parameters
self.eng.eval("set_param(model, 'StopTime', '10')", nargout=0)
self.eng.eval("set_param(model, 'FixedStep', '0.1')", nargout=0)
# Start the simulation and instantly pause
self.eng.eval("set_param(model, 'SimulationCommand', 'start')", nargout=0)
self.eng.eval("set_param(model, 'SimulationCommand', 'pause')", nargout=0)
def simulate(self):
# Control Loop
while self.eng.get_param(self.modelName, 'SimulationStatus') not in ('stopped', 'terminating'):
# Continue the simulation
self.eng.eval("set_param(model, 'SimulationCommand', 'continue')", nargout=0)
def getOutput(self):
# simout=self.eng.workspace['out.simout']
simout_S =self.eng.eval("out.simout", nargout=0)
tout_T = self.eng.eval("out.tout", nargout=0)
# tout = self.eng.workspace['out.tout']
return simout_S, tout_T
def disconnect(self):
# Stop the simulation and close Matlab connection
self.eng.eval("set_param(model, 'SimulationCommand', 'stop')", nargout=0)
self.eng.quit()
# Instantiate the SimulinkPlant object
plant = SimulinkPlant(modelName="ToyExample_V2")
# Connect to Matlab and set input value, simulation time, and timestep
plant.connectToMatlab()
# Start simulation
plant.simulate()
outputSim, timeT = plant.getOutput()
print('Simulation Output')
print(outputSim)
print('Time')
print(timeT)
# Close connection to MATLAB
plant.disconnect()
但是,运行此代码后,我的输出变量
outputSim
和timeT
没有得到任何结果。我得到 'None
' 结果如下:
Starting Matlab
Connected to Matlab
Initialized Model
Simulation Output
None
Time
None
如何获取输出变量中的结果值?
你有没有以某种方式解决它,我收到同样的