Simulink, receive data from Python Script

7 vues (au cours des 30 derniers jours)
jorge varona madrid
jorge varona madrid le 18 Oct 2020
Réponse apportée : Satwik le 24 Mar 2025
Hi, I have desing a model in order to control a simulator with simulink, but the data which I want to reproduce is from a PC game,
I have obtain this data on a python Script from the Sharedmemory. Is there any method to send this data from the Script to Simulink, or
directly read the data from the sharedmemory with Simulink?
Thanks, for your time.

Réponses (1)

Satwik
Satwik le 24 Mar 2025
Here are some methods which can be leveraged to integrate data from a Python script into Simulink:
1) MATLAB Engine for Python: the MATLAB Engine API for Python can be used to send data from a Python script to MATLAB, which can then be used in Simulink.
  • Install the 'MATLAB Engine' using the following command in your terminal or command prompt:
>> python -m pip install matlabengine
  • Modify the Python script to send data to MATLAB using the MATLAB Engine API.
import matlab.engine
import numpy as np
% Start MATLAB engine
eng = matlab.engine.start_matlab()
% Create a numpy array in Python
py_array = np.linspace(0.0, 6.28, 1000)
% Convert numpy array to a MATLAB array
matlab_array = matlab.double(py_array.tolist())
% Put the array into the MATLAB workspace
eng.workspace['mx'] = matlab_array
% Stop MATLAB engine
eng.quit()
For detailed information on the 'MATLAB Engine API' please refer to the foloowing documentation: https://www.mathworks.com/help/matlab/apiref/matlab.engine.matlabengine-class.html
2) File-Based Communication: write the data into a .CSV or .MAT file in Python and read it from Simulink.
  • Write data to a .CSV or .MAT file
import numpy as np
import scipy.io
% Example data
data = np.random.rand(10) % Replace with your actual data
% Save to MAT file
scipy.io.savemat('sim_data.mat', {'sim_data': data})
I hope this proves useful!

Catégories

En savoir plus sur Call Python from MATLAB dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by