Why does accessing Python object in Simulink error with "Attempt to extract field 'path' from 'mxArray'."
5 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
MathWorks Support Team
il 18 Feb 2025
Modificato: MathWorks Support Team
il 17 Mar 2025
Questo/a domanda è stato/a segnalato/a da 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'.'
Risposta accettata
MathWorks Support Team
il 14 Mar 2025
Modificato: MathWorks Support Team
il 17 Mar 2025
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 Commenti
Più risposte (0)
Vedere anche
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!