Data from simulink to python with "To Workspace" block

5 ビュー (過去 30 日間)
Patrick
Patrick 2021 年 1 月 23 日
コメント済み: Shubham 2025 年 1 月 16 日
Hi everyone,
I would like to use a controller written in python for a simulink enviornment and therefore I am using the python matlab API. But the problem is how do i get information (state information for each time step) from the simulink enviornment to my python script. I have tried the following in python:
import matlab.engine
import matplotlib.pyplot as plt
eng = matlab.engine.start_matlab()
modelName = 'plant'
eng.eval("model = '{}'".format(modelName), nargout=0)
eng.eval("load_system(model)", nargout=0)
# Initialize Control Action to 0
u = 0
eng.set_param('{}/u'.format(modelName), 'value', str(u), nargout=0)
print("Initialized Model")
# Start Simulation and then Instantly pause
eng.set_param(modelName, 'SimulationCommand', 'start', 'SimulationCommand', 'pause', nargout=0)
print(eng.who())
eng.set_param(modelName, 'SimulationCommand', 'stop', nargout=0)
eng.quit()
The simulink model "plant" is attached where I use "To workspace" block to load the data in to the workspace. But I don't know how to get the data now of the object "eng.workspace['out']"
MATLAB version: R2020b
Python: 3.7.9
Thanks in advance

採用された回答

Deepak Meena
Deepak Meena 2021 年 1 月 31 日
編集済み: Deepak Meena 2021 年 2 月 1 日
Hi Patrick,
Out is the variable which store the output of the To workspace block. By default the variable would be if type of Timeseries. To change it to array , go to block parameter->save format , change it to Array.
Now out contains many variable , but the variable you are looking for would be out.simout , so to access that in python:
p = eng.workspace['out.simout'];
  1 件のコメント
Shubham
Shubham 2025 年 1 月 16 日
Hello, I am trying the same thing. It still won't let me get access to workspace variable. Not sure what I am doing wrong. Does the version of Python kernel matter? Mine is 3.11 but the link here says it has to be 3.7 How to Interact with Simulink Using Python - File Exchange - MATLAB Central.
Would appreciate your help!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeCall MATLAB from Python についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by