Why does accessing Python object in Simulink error with "Attempt to extract field 'path' from 'mxArray'."
6 ビュー (過去 30 日間)
古いコメントを表示
MathWorks Support Team
2025 年 2 月 18 日
編集済み: MathWorks Support Team
2025 年 3 月 17 日
この 質問 は Walter Roberson
さんによってフラグが設定されました
I'd like to import a Python module in Simulink, and then use the properties/functions of the module. In this example, I want to access the properties and call functions of "out_class_instance".
function out_class_instance = my_matlab_func()
coder.extrinsic('py.my_python_file.my_python_class')
out_class_instance = py.my_python_file.my_python_class('exampleInput');
end
When using either a 'MATLAB Function' or 'MATLAB System' block, I get the following error message:
Simulink detected an error 'Attempt to extract field 'path' from 'mxArray'.'
採用された回答
MathWorks Support Team
2025 年 3 月 14 日
編集済み: MathWorks Support Team
2025 年 3 月 17 日
This error occurs because the Simulink model is using code generation. When using 'coder.extrinsic', the model imports the Python class instance as an 'mxArray', instead of a Python object. This occurs with both MATLAB Function and System blocks.
To access Python objects in Simulink workflows, use a System block. Remove any calls to 'coder.extrinsic' and ensure the system block property 'simulate using' is set to 'interpreted execution'. Take the example Python Code:
class person:
def __init__(self, name):
self.name = name
self.age = 0
def getAge(self):
return self.age
def haveBirthday(self):
self.age += 1
In a separate file, create a MATLAB function to return an instance of this class.
function person_instance = my_matlab_func()
person_instance = py.my_python_file.person('Jane Doe');
end
Create a custom MATLAB System class component to be used by the System block. Assign the imported Python module to a private property of this MATLAB class. Include needed Propagation Methods in the class definition.
classdef myComponent < matlab.System
properties (Access = private)
MyPerson
end
methods (Access = protected)
function setupImpl(obj)
obj.MyPerson = my_matlab_func();
end
function [y] = stepImpl(obj, x)
% access property
y = x;
obj.MyPerson.haveBirthday();
disp(obj.MyPerson.getAge());
end
% 'Propagation Methods'
function out = getOutputSizeImpl(obj)
% Return size for each output port
out = [1 1];
end
function out = getOutputDataTypeImpl(obj)
out = 'double';
end
function out = isOutputComplexImpl(obj)
out = false;
end
function out = isOutputFixedSizeImpl(obj)
out = true;
end
end
end
0 件のコメント
その他の回答 (0 件)
参考
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!