How to pass python objects to Matlab function block

11 次查看(过去 30 天)
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 个)

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 CenterFile Exchange 中查找有关 Call 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