How to call properly python objects from simulink ?

11 次查看(过去 30 天)
Hi everyone,
I have a python code that includes a class with default values and functions. Using matlab command line I am able to create object and do my opeartions properly.
Just like
myObject = py.myCode.myClass();
myObject.begin();
disp(myObject.arbitraryParameter);
Also I have a simulink model that I want to run according to the outputs of my python functions. But, unfortunately when I try to run my code I have faced a problem which signify that in simulink I can not create a python object. The code is something like :
function y = fcn(u)
coder.extrinsic('py.myCode.myClass');
myObject = py.myCode.myClass();
y = 0;
y = myObject.arbitraryParameter;%Parameter is numeric. This is the line that gives the error
and I am getting the following error : Attempt to extract field 'arbitraryParameter' from 'mxArray'.
I tried a lot of different things but could not figure out what is the problem.
Do you have any advice about that?

回答(2 个)

Aakash Garg
Aakash Garg 2021-3-30
There are two things need to be modified when a third party tool function is used in the MATLAB Function Block:
(1) Using coder.extrinsic
In Simulink, when you have a MATLAB function block, in order to have it to be integrated with Simulink, this MATLAB function block needs to be compile to have a MEX file. This is not an issue for any in-house MATLAB command. However, for a python function, it becomes an issue since the engine does not know how to MEX the .py code. As the error message suggested, you can consider to use 'coder.extrinsic' to tell the MATLAB Function block not to MEX certain line of code with Python. In this way, that line of code will be dispatched to and executed inside the MATLAB environment, and not the Simulink environment. Here is the documentation about this function.
(2) Preinitialize the variable to which it is assigned.
Wrap the whole script to a M-function and just call it once inside the MATLAB Function Block:
This way, all the internal Python will be calculated in the MATLAB engine and only the output y is used in the Simulink simulation.
Here is a similar case using MATLAB Function block, same workflow, the only difference is the third party tool

Erfan Tajalli
Erfan Tajalli 2022-9-6
Dear Ahmet,
It might be so late to answer this question for you, however future readers can take benefit of it.
If you are receiving this error (Attempt to extract field 'arbitraryParameter' from 'mxArray), I can assume that you are using "MATLAB Function" block in your Simulink model. If you replace this block with "Interpreted MATLAB Function", you will not get that error anymore.
The MATLAB version I am using is R2022a and Python version 3.8.

类别

Help CenterFile Exchange 中查找有关 Call Python from MATLAB 的更多信息

产品


版本

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by