Use python(cPickle, Sympy, Aesara) in matlab and simulink.

35 次查看(过去 30 天)
Hi,
I wan to use serizalized funcion in matlab and simulink.
Minimum viable code like this
test.py
from six.moves import cPickle
# SymPy -> Aesara translater, bundled with SymPy.
from sympy.printing.aesaracode import aesara_function
# Arbitrary SymPy expression.
from sympy import sin
from sympy.abc import x
expr = sin(x)/x
# GPU-parallelized Aesara function compiled from that expression! Yup.
f = aesara_function([x], [expr])
g = open('obj.save', 'wb')
cPickle.dump(f, g, protocol=cPickle.HIGHEST_PROTOCOL)
g.close()
script.m
pyrun('test.py')
error message is
"Warning: Unable to load Python object. Saving (serializing) Python objects into a MAT-file is not supported.
Error using <string>><module> (line 1)
Python Error: NameError: name 'test3' is not defined"
+Dependancy: python3.10, matlab 2024a

采纳的回答

Rushikesh
Rushikesh 2024-9-6,12:14
I understand that you are trying to run python file from MATLAB and you want to load Python object in MATLAB.
As per code provided by you, you are trying to use ‘pyrun’ function to call python interpreter and run python file. But ‘pyrun’ function is meant to execute python code written inside it, not files. To run python files, you can use ‘pyrunfile function.
pyrunfile("test.py") %for example
To learn more about ‘pyrunfile’ function, you can refer documentation given below:
Further more, I see that you are trying to load python object in MATLAB and further intended to use it from MATLAB. For that, you can directly use python code inside MATLAB using "py." prefix.
For example, you can refer to MATLAB code given below, which will give you expected output:
file = py.open('obj.save', 'rb');
loaded_function = py.pickle.load(file);
input_value = 1.0; % Example input
result = loaded_function(input_value)
The above code works for the test file given by you along with python 3.10.14 and MATLAB R2024a. I have also attached the MATLAB output below for your reference.
You can refer to documention given below to learn more about accessing Python modules from MATLAB.
Hope this helps you and you can proceed further.

更多回答(0 个)

类别

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

标签

产品


版本

R2024a

Community Treasure Hunt

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

Start Hunting!

Translated by