MATLAB Answers

How to import symbolic expressions from Python to MATLAB?

79 views (last 30 days)
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?


Sign in to comment.

Accepted Answer

Michael Croucher
Michael Croucher on 27 Sep 2020
Edited: Michael Croucher on 27 Sep 2020
Imagine your friend had a Python function that created that expression. Let's call it create_symbolic_expression() and put it into a file My demonstration is likely to be more simple than the one you have in mind. 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
from sympy import lambdify
from 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
def lambdify_expression(expr):
We can now go to MATLAB, ensure 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
ans =

More Answers (0)




Community Treasure Hunt

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

Start Hunting!