Main Content

Call Python Function Using MATLAB Function and MATLAB System Block

This example shows how to call a Python® function in Simulink® that sorts random numbers using a Python® sorting function and two different blocks: the MATLAB Function block and MATLAB System block. For more on using Python in MATLAB®, see Access Python Modules from MATLAB - Getting Started.

MATLAB supports the reference implementation of Python, often called CPython. If you are on a Mac or Linux® platform, you already have Python installed. If you are using Windows®, you need to install a distribution, such as those found at For more information, see Configure Your System to Use Python.

Use Python Functions in Simulink Model

This model contains a random number generator that outputs a 1x5 double containing numbers from 0 to 1, a MATLAB Function and a MATLAB System block that sorts the numbers, and a manual switch that leads to a Display block.

The MATLAB Function block calls the py.sorted function from Python and outputs a 1x5 double sorted list, as seen below in the code snippet.

function y = fcn(u)
    % Sort values of 'u'
    ytmp = py.sorted(u);

The MATLAB System block calls the py.sorted function as part of stepImpl and outputs a 1x5 double sorted list as seen below in the code snippet.

function y = stepImpl(~,u)
    % Implement algorithm. Calculate y as a function of input u and
    % discrete states.
    y = py.sorted(u);
    y = cellfun(@double,cell(y));

Running this model using the MATLAB Function block or MATLAB System block yields a sorted list of the numbers generated in the random number generator block. An example of this can be seen below.