Articles & Tutorials

Integrating Python into MATLAB

We often need to create code using a mixture of languages such as C++, Python and MATLAB.  Each language has its own strengths and weaknesses but creating a single program in a mix of languages is typically difficult.  MATLAB has had, forever, a MEX interface that allowed C, C++ and Fortran functions to be called from MATLAB, and for a while some limited support to call Python code.

MATLAB R2019a introduced a new mechanism to connect Python code that allows user written Python classes to appear inside MATLAB just like native MATLAB classes. Consider a very simple example:

class Rectangle:
    def __init__(self, x, y, w, h):
        self.x = x
        self.y = y
        self.w = w
        self.h = h
    def Area(self):
        return self.w * self.h

We invoke the Python constructor code by

>> r = py.rectangle.Rectangle(1, 2, 3, 4)
r = 
  Python Rectangle with properties:
    y: 2
    h: 4
    x: 1
    w: 3
    <rectangle.Rectangle instance at 0x177d056c8>

and the result is a MATLAB object with properties that reflect the Python class attributes as well as the class methods.

We can invoke the Python code to compute area by

>> r.Area
ans =

We can display or change the class properties (underlying Python class attributes)

>> r.x
ans =

>> r.w = 4;

and as expected the computed area is now different

>> r.Area
ans =

We can similarly construct an instance of a NumPy ndarray from a MATLAB vector

>> a = py.numpy.array([1 2 3])
a = 
  Python ndarray:
     1     2    3

    Use details function to view the properties of the Python object.
    Use double function to convert to a MATLAB array.

which has a very large number of methods.  Conversely, we can create a MATLAB vector from the NumPy object by

>> double(a)
ans =

     1     2     3

All of this makes is really easy to exploit existing packages written in Python while keeping the convenience of the interactive MATLAB development process, high-quality graphics, powerful toolboxes and interactive notebooks (called LiveScripts in MATLAB speak).  Interestingly all of this works in MATLAB Online as well (the cloud version of MATLAB which runs under Linux on AWS) which means you can share your code to a colleague and have it appear in their MATLAB cloud drive (a bit like shared folders on Dropbox) from where it can be run.

View all posts