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

10 Ansichten (letzte 30 Tage)
younghwa park
younghwa park am 6 Sep. 2024
Beantwortet: Rushikesh am 6 Sep. 2024
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

Akzeptierte Antwort

Rushikesh
Rushikesh am 6 Sep. 2024
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.

Weitere Antworten (0)

Kategorien

Mehr zu Call Python from MATLAB finden Sie in Help Center und File Exchange

Produkte


Version

R2024a

Community Treasure Hunt

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

Start Hunting!

Translated by