How to pass python objects to Matlab function block

11 vues (au cours des 30 derniers jours)
Alessandro
Alessandro le 10 Août 2023
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 commentaire
Ayush
Ayush le 21 Août 2023
Could you please share your model? We need to see where exactly the error occurs.

Connectez-vous pour commenter.

Réponses (1)

Gagan Agarwal
Gagan Agarwal le 21 Sep 2023
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!

Catégories

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

Produits


Version

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by