Today I’ve learned how to load Python into MATLAB and how to run scripts written in Python in MATLAB. Yey! Big deal.
Before I continue, I must confess that I’m a daily MATLAB user but I’ve barely touched Python in my life. So, I’ve struggled a little bit this afternoon when I was trying to load the correct version of Python into MATLAB. I’m pretty sure that there are more people out there like me who have been in the same place, and that will be as well. Here, I would like to give a small tutorial with the correct steps to succeed in do it (for a future me that might need the info again and for whoever might be interested in these steps).
So, here we go!
Note that I’ll explain the steps from a Windows operating system perspective. Also, I’ve added (!) signs when there’s an important detail to take much into account to complete the steps and finally make Python work into MATLAB. These were actually the steps that I didn’t pay attention to and it made me spent the whole afternoon to achieve my goals.
(!) Important note before we start:
- MATLAB does not support the python from Anaconda, so you will have to be sure to install python another way! This is what we’ll do in the following steps.
- Only >= version 3.5 in Python will work in MATLAB.
Setting up Python
- Download Python. Make sure that you download the correct version of Python from python.org for your operating system (in my case, Windows) and that you run the correct installer (‘python-3.8.2-amd64_windows.exe’).
(!) Check the box “Add python 3.8 to PATH”. Then click “Install now”.
- Check the python version you have from the command prompt. To make sure you’ve downloaded Python correctly you can open the command prompt and type the following code:
- Install ‘cPython’ package from the command prompt. When completing the installation, you should install the ‘cPython‘ package from the command prompt using the following command:
pip install cpython
- [Optional] Install other packages from the command prompt. When completing the installation, you can install other packages that might interest you (e.g., matplot, mne,…) from the command prompt using the same command and changing the package name for the proper one:
pip install mne pip install fooof
- If you have any trouble completing these steps, you can always check this tutorial on “Using Python on Windows”.
Loading Python into MATLAB
Here it comes the moment of the truth:
- Launch MATLAB.
- Check if MATLAB has loaded Python. Run the following command in the Command window of MATLAB:
- If you have Anaconda downloaded, make sure you tell MATLAB the correct location of the file by adding the correct path of the executable python.exe.
- Now, you should be good to go!
I hope you find this post as useful as I found it when looking for the best way to launch Python scripts and functions into MATLAB.
Feature image from Pexels – C0 license.