How to initialize Sympy python function in Simulink
Show older comments
Hello,
I want to solve ODE in Simulink with python function (derived in Sympy). This is just example, real Sympy equations will be larger.
Python function called Pyfun.py:
from sympy import lambdify, Matrix, symbols
t,x1,x2 = symbols('t x1 x2')
def create_symbolic_expression():
expr = Matrix([[x2], [(1-x1**2)*x2-x1]]);
return expr
def lambdify_expression(expr):
return(lambdify([t,x1,x2],expr, modules='numpy'))
Then I have MATLAB Function in Simulink that looks like this
function y = fcn(t,u)
y = [0;0];
coder.extrinsic('py.Pyfun.create_symbolic_expression')
coder.extrinsic('py.Pyfun.lambdify_expression')
expr = py.Pyfun.create_symbolic_expression();
myfunc = py.Pyfun.lambdify_expression(expr);
y = double(myfunc(t,u(1),u(2)));
Output of this function is integrated and going back as input, as it should. Everything here works well and gives right results.
My problem is, that the MATLAB Function is calling the "create" and "lambdify" symbolic expression every iteration and it makes the calculation very slow. The question is, if there is a way to initialize the python code before the Simulink simulation and only calculate with "myfunc" expression/function. I tried to call this in InitFcn in Callbacks like this
coder.extrinsic('py.Pyfun.create_symbolic_expression')
coder.extrinsic('py.Pyfun.lambdify_expression')
expr = py.Pyfun.create_symbolic_expression();
myfunc = py.Pyfun.lambdify_expression(expr);
and run MATLAB Function only like this
function y = fcn(t,u)
y = [0;0];
y = double(myfunc(t,u(1),u(2)));
but it says "Undefined function or variable 'myfunc'.". Thank you.
Accepted Answer
More Answers (0)
Categories
Find more on Classical Control Design in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!