How to call properly python objects from simulink ?
조회 수: 6 (최근 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?
댓글 수: 0
답변 (2개)
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
댓글 수: 0
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.
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Call Python from MATLAB에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!