How to pass python objects to Matlab function block

10 ビュー (過去 30 日間)
Alessandro
Alessandro 2023 年 8 月 10 日
回答済み: Gagan Agarwal 2023 年 9 月 21 日
I have built a Simulink library in which I need to pass a python object to an inner Matlab function block.
The python object is initialized in an initialization script.
I've created a mask in my library in which this object is passed and then I created a mask for the matlab function block for the same reason. Then, following this documentation page, I've setup this object as a parameter of the function.
When I try to run the simulation I get the following error:
Expression 'FIELD' for initial value of data 'FIELD' must evaluate to logical or supported numeric type.
  1 件のコメント
Ayush
Ayush 2023 年 8 月 21 日
Could you please share your model? We need to see where exactly the error occurs.

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

回答 (1 件)

Gagan Agarwal
Gagan Agarwal 2023 年 9 月 21 日
Hi Alessandro
I understand that you want to pass python object to the ‘MATLAB function block’ and since python objects are not a supported data type in MATLAB you are encountering the mentioned error.
The functionality to directly pass a Python object to a ‘MATLAB function block’ is not available.
However, you can implement a workaround by creating a wrapper function in python script which will allow you to transmit the object data to the MATLAB workspace. Once the data is available in the MATLAB workspace, it can then be passed to the 'MATLAB function block' as needed.
Here's an example of how you can create and use the wrapper function in your ‘.py’ script:
import matlab.engine
eng = matlab.engine.start_matlab()
class MyClass:
x = 5
y = 10
def pyfun(p1):
op = eng.myfun(p1.x, p1.y)
print(op)
p1 = MyClass()
pyfun(p1)
In the above code, the Python object is passed to a wrapper function called 'pyfun'. This wrapper function, in turn, transmits the object data to the MATLAB function 'myfun', making the object data accessible within the MATLAB workspace from where the data can now be transmitted to the ‘MATLAB function block’ as needed.
I hope this helps!

カテゴリ

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