This example shows how to compile MATLAB code with a Python dependency into a Python 3 module. The files for this example can be downloaded from Python-Compile-Example and contains the following files: - pyPrimesList.m – MATLAB function that calls the Python function mw_module.prime_ops.py to get the first n prime numbers
- mw_module.prime_ops.py – Python function called by pyPrimesList.m; belongs to the module mw_module
- buildscript.m – MATLAB script to compile pyPrimesList.m into a Python package
- py_primescompdriver.py – Compiled Python script to call the MATLAB function pyPrimesList
The MATLAB code (pyPrimeList.m) takes a single input argument n and lists the first n prime numbers. For example, to list the first 8 prime numbers:
>> pyPrimesList(8)
ans =
1×8 int32 row vector
2 3 5 7 11 13 17 19
pyPrimeList.m has a dependency on the Python module mw_module, which includes prime_ops.py.
To Compile
- Start MATLAB and cd to the root folder of the files above
- Run buildscript.m to compile the MATLAB function pyPrimesList into a python package
The buildscript.m code uses mcc to compile pyPrimeList.m as a Python module named py_primescompdriver.py.
>> mcc '-W' 'python:py_primescomp' 'pyPrimesList.m' '-v' '-a' 'mw_module' '-w' 'off:MATLAB:hg:AutoSoftwareOpenGL'
In the command, above:
- The '-W' 'python:py_primescomp' option specifies that we are creating a Python module named py_primescomp
- The '-a' 'mw_module' option adds the files in folder mw_module to the deployable archive. This is how the Python code called by MATLAB is included in the Python package.
- The '-w' 'off:MATLAB:hg:AutoSoftwareOpenGL' option turns off MATLAB warnings related to OpenGL rendering.
To Run
Follow the steps below to run this example.
- Install MATLAB Runtime
- Bring up a command window.
- Run the command below to install the Python package generated in the previous step.
$ python setup.py install
- Run the command below to call the MATLAB function pyPrimesList.
$ python py_primescompdriver.py