Import Python user modules in Matlab

This example shows how to:

  1. setup Matlab with user Python install (e.g. Anaconda Python)
  2. import Python user modules (e.g. made yourself or from Github).

Example assumes Anaconda/Miniconda Python.

  1. setup Python user module. Let’s say you want to use ESPRIT in Python from Matlab
    git clone https://github.com/scivision/signal_subspace
    cd signal_subspace
    pip install -e .
    
  2. from Matlab
    pyversion ~/miniconda/bin/python
    py.signal_subspace.esprit()
    

    Python Error: TypeError: esprit() missing 2 required positional arguments: ‘x’ and ‘L’

Notes

  • you do not import Python modules with Matlab, the Python module import is implicit in the module function call
  • Python executable choice persists across Matlab sessions.

reference

Troubleshooting

If you get

Error using pyversion Path argument does not specify a valid executable.

To fix by manually overriding the Python executable path, in your matlab.settings (on Linux, this is under ~/.matlab/R2017b/matlab.settings (assuming Linux username joe) you must have a section like:

<settings name="external">
    <settings name="interfaces">
        <settings name="python">
            <key name="Version">
                <string minArraySize="4" maxArraySize="4">
                    <value><![CDATA[3.6]]></value>
                    <value><![CDATA[/home/joe/anaconda3/bin/python]]></value>
                    <value><![CDATA[/home/joe/anaconda3]]></value>
                    <value><![CDATA[/home/joe/anaconda3/lib/libpython3.6m.so]]></value>
                </string>
            </key>
        </settings>
    </settings>
</settings>

Note: You can force Python 3.6 to work with Matlab < R2017b this way.

reference

Tags:

Categories:

Updated:

Leave a Comment