Accessing a running MATLAB object from Python

31 ビュー (過去 30 日間)
Rob Campbell
Rob Campbell 2022 年 12 月 22 日
編集済み: Rob Campbell 2023 年 1 月 1 日
I have a MATLAB class that runs some hardware. I use it as an API by other code in order to build small MATLAB applications. I have some users who want some of the functionality available in Python. It's quite a lot of work to redo everything in Python (there is also a GUI) so I'm looking into the possibility of making the API available in Python somehow.
Here is what I'm looking to do: I want to instantiate my class in MATLAB and have the user set everything up. I'm then wondering if it's possible for Python to somehow access this workspace and run methods of the instantiated object. It seem unlclear me, though, if the if matlab.engine can do that. Does anyone know?
If that is not possible, what might be a good alternative? Maybe through TCP IP if I write a suitable server/client system? I've not done that before, though, and don't know where to start.
Any other options?

採用された回答

Vijay
Vijay 2022 年 12 月 26 日
Yes, you can connect from python to a running instance of MATLAB and execute commands and access workspace variables.
Follow below steps
  1. First, convert your MATLAB session to a shared session by executing the below command in MATLAB
matlab.engine.shareEngine
2. connect to the shared MATLAB session by connect_matlab function from python API
Example:
import matlab.engine
eng = matlab.engine.connect_matlab()
eng.sqrt(4.0)
You can use eng.eval function to execute any commands in MATLAB.
Please refer to the following link for more information Connect Python to Running MATLAB Session - MATLAB & Simulink - MathWorks India.
Hope that helps!
  1 件のコメント
Rob Campbell
Rob Campbell 2022 年 12 月 26 日
編集済み: Rob Campbell 2023 年 1 月 1 日
I tried this and can indeed access the workspace of a running session. What seems to work for me (at least with a toy example) is:
  • I create an instance of a class, let's call it myS, in MATLAB.
  • I see it's there in Python with eng.who()
  • Then I pull the object into Python: localS = eng.workspace["myS"]
  • To run a method the call is a little weird, but it works: eng.myMethod(localS,INPUT_ARG,nargout=0)

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

その他の回答 (0 件)

カテゴリ

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

製品


リリース

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by