Use python(cPickle, Sympy, Aesara) in matlab and simulink.
조회 수: 10 (최근 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
댓글 수: 0
채택된 답변
Rushikesh
2024년 9월 6일
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
추가 답변 (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!