필터 지우기
필터 지우기

How to import symbolic expressions from Python to MATLAB?

조회 수: 29 (최근 30일)
Sayan Batabyal
Sayan Batabyal 2020년 9월 21일
댓글: Benedikt 2023년 8월 30일
One of my colleagues is using Python(more specifically SymPy) to generate a very big symbolic expression. Now, I want to perform some numerical computations on the expression in MATLAB. How can I export the expression from Python and import it in MATLAB?

채택된 답변

Michael Croucher
Michael Croucher 2020년 9월 27일
편집: Michael Croucher 2020년 9월 27일
Imagine your friend had a Python function that created that expression. Let's call it create_symbolic_expression() and put it into a file sympy_demo.py. My demonstration is likely to be more simple than the one you have in mind.
sympy_demo.py also contains a function that lambdify's this symbolic expression..that is, it creates a Python function in the variables x,y and z.
%This is the contents of sympy_demo.py
from sympy import lambdify
from sympy.abc import x,y,z
def create_symbolic_expression():
'''
This is a proxy for whatever code your friend has written but I'll keep it simple for this demo.
'''
expr = x+y+z
return(x+y+z)
def lambdify_expression(expr):
return(lambdify([x,y,z],expr))
We can now go to MATLAB, ensure sympy_demo.py is on your path and do
import py.sympy_demo.create_symbolic_expression
import py.sympy_demo.lambdify_expression
expr = create_symbolic_expression() %This is a Python object in MATLAB that represents the symbolic expression
myfunc = lambdify_expression(expr) %Turn it into a Python function that can be evaluated in MATLAB
We can now evaluate myfunc with numeric inputs
myfunc(1,2,3)
ans =
6
  댓글 수: 2
Sayan Batabyal
Sayan Batabyal 2020년 9월 28일
Thanks for your answer. It worked.
Benedikt
Benedikt 2023년 8월 30일
The % character in sympy_demo.py produces an error. Use # for python comment.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Call Python from MATLAB에 대해 자세히 알아보기

제품


릴리스

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by