by Al Danial

Set up a MATLAB+Python environment

Part 1 of the Python Is The Ultimate MATLAB Toolbox series.

What you’ll need

  • MATLAB version 2020b or newer (some MATLAB versions older than 2020b support Python, but the farther back you go, the more more limitations and problems you’ll hit). The latest release, 2022a, is definitely recommended.
  • A Python installation supported by your version of MATLAB. I strongly recommend the Anaconda Python distribution 1 for two reasons: 1) it comes with a deep stack of Python modules and external tools useful for scientific computing and 2) its conda command has the ability to create virtual environments with specific shared library versions. Control over shared library versions in Python is invaluable for troubleshooting MATLAB errors (or crashes) when importing complex modules such as NumPy, SciPy, and statsmodels (among others) in MATLAB.

Step 1: pyenv

The first command to issue in a MATLAB console is pyenv. It will either come up empty, or it will print information about the Python installation MATLAB found:

>> pyenv
ans = 

  PythonEnvironment with properties:

          Version: "3.9"
       Executable: "/usr/local/anaconda3/2021.05/envs/matpy/bin/python"
          Library: "/usr/local/anaconda3/2021.05/envs/matpy/lib/libpython3.9.so"
             Home: "/usr/local/anaconda3/2021.05/envs/matpy"
           Status: Loaded
    ExecutionMode: InProcess
        ProcessID: "840228"

If pyenv comes up empty, set 'Version' to the path of the Python executable you want to use:

>> pyenv('Version', "/usr/local/anaconda3/2021.05/envs/matpy/bin/python")

On a Windows computer your entry might be

>> pyenv('Version', "C:/ProgramData/Anaconda3/python.exe")

(Yes, forward slashes work in Windows too.)

The best way to have MATLAB recognize a specific virtual environment is to first activate the virtual environment in a terminal, then start MATLAB from that terminal.

Step 2: Does it work?

A quick way to determine if your MATLAB and Python environments are compatible is to import the NumPy module into MATLAB:

>> np = py.importlib.import_module('numpy')

NumPy and MATLAB have several shared libraries in common so importing NumPy into MATLAB is a good litmus test for overall MATLAB/Python compatibility. Several things may happen:

  1. A long list of function names appears.
  2. Python Error: ImportError
  3. Unable to resolve the name numpy
  4. Segmentation violation detected

The first case indicates the import was successful. If you see the functions, congratulations, you should be able to use MATLAB and Python together effectively.

The last three errors can be caused by a Python installation that is not version-consistent with, or not visible to MATLAB; the Python installation does not have NumPy installed; or you need to create a virtual environment configured with shared library versions that are consistent with MATLAB’s shared libraries.

Possible work-arounds to library conflicts:

  1. Change the ExecutionMode setting to OutOfProcess ExecutionMode: InProcess

    >> pyenv("ExecutionMode","OutOfProcess") 

  2. Create a conda environment with library versions that more closely match MATLAB’s. Unfortunately there’s no obvious way to identify either the libraries or the versions so experimentation is needed. The conda environment that works well for me with MATLAB 2020b is

    Linux (Ubuntu 20.04) + MATLAB 2020b

    conda create --name matpy python=3.8.8 libgcc-devel_linux-64=8.4.0  \
        libgcc-ng=8.4.0 geopandas matplotlib pulp cartopy austin faker  \
        pint poliastro psycopg2 pymongo pythran redis redis-py simanneal \
        netCDF4 descartes h5py statsmodels pyyaml psutil lxml dask       \
        distributed paramiko sympy requests pyflakes uncertainties seaborn \
        cython pytest scikit-umfpack ipython -c conda-forge
        

    Windows 10 + MATLAB 2020b

    conda create --name matpy python=3.8.8 geopandas matplotlib pulp ^
        cartopy faker pint poliastro psycopg2 pymongo pythran redis  ^
        redis-py statsmodels simanneal netCDF4 descartes h5py pyyaml ^
        psutil lxml dask distributed paramiko sympy requests pyflakes ^
        cython uncertainties seaborn pytest ipython -c conda-forge
        

    macOS (Catalina, Big Sur) + MATLAB 2020b

    conda create --name matpy python=3.8.8 geopandas matplotlib pulp \
        cartopy austin faker intel-openmp=2021.2.0 llvm-openmp=10.0.0 \
        libllvm10=10.0.1 llvmlite=0.36.0 \
        pint poliastro psycopg2 pymongo pythran redis redis-py simanneal \
        netCDF4 descartes h5py statsmodels pyyaml psutil lxml dask       \
        distributed paramiko sympy requests pyflakes uncertainties seaborn \
        cython pytest ipython -c conda-forge
        

I’ve found MATLAB 2022a to work cleanly with the base Anaconda 2021.05 installation; no finely-tuned conda environment needed.


  1. free for individual use but requires a purchased license for commercial use ↩︎