Import Python user modules from Matlab

Setup Matlab to use your user Python install (e.g. Anaconda Python) and import your own modules (e.g. some Python module you made yourself or got from Github). Here we assume you have Anaconda/Miniconda Python and are using Matlab R2017a.

  1. From Terminal/Command Prompt:

     conda create -n py35 python=3.5
     source activate py35
    
  2. setup your 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
     python setup.py develop
    
  3. from within Matlab

     pyversion ~/miniconda/envs/py35/bin/python
     py.signal_subspace.esprit()
    

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

Notes

  • you do not import with matlab, the import is implicit in the call
  • This setting persists across Matlab sessions.

reference

Troubleshooting Python not found

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/R2017a/matlab.settings (assuming Matlab R2017a, and 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 how I forced Python 3.6 to work this way, even though Matlab R2017a only officially supports up to Python 3.5.

reference