MATLAB is running the wrong version of Python

14 views (last 30 days)
I am working on a project in MATLAB (on a fully-updated Mac) but need some functions from a C++ library with Python bindings (the specific library is linked here). I know that MATLAB supports Python modules, but I am having trouble loading an important Python library in MATLAB.
I think that the problem could be that MATLAB is loading an incorrect version of Python. As was mentioned in the documentation, I ran the following command in the MATLAB command window:
pe = pyenv;
pe.Version
This yielded "2.7". However, the default version of Python in my terminal is 3.8.5. This version of Python supports the library I need for my project. I have checked this by running the following lines in Terminal:
python
import annoy
Moreover, I'm able to correctly use the library annoy when solely coding in Python (e.g., in a Jupyter notebook). So, I think that the library is not installed correctly on the version of Python that MATLAB is running.
I have tried changing the version of Python used by MATLAB as follows:
pyenv('Version','3.8')
However, I get the following error message, so I believe that MATLAB isn't aware that I have Python 3.8 installed.
Error using pyenv
Cannot find specified version.
I would appreciate any guidance on how to get MATLAB to run the correct version of Python (the one in which the necessary library is installed). How should I go about fixing this? Why is MATLAB running a different version of Python in the first place?
  2 Comments
Steven Lord
Steven Lord on 17 Mar 2021
The first release of MATLAB that supports using version 3.8 of Python is release R2020b. Which release are you using?
Samuel L. Polk
Samuel L. Polk on 17 Mar 2021
Thank you for your comment! I am using R2020b.

Sign in to comment.

Answers (1)

Rashed Mohammed
Rashed Mohammed on 19 Mar 2021
Hi Samuel,
You can find the python3 executable path using the which command as follows
which python3
and use the path given by the above command to configure MATLAB to use python 3 as follows
pe = pyenv('Version','<path_of_python3_executable>')
Note that this will be persisted across MATLAB sessions, so you don't have to perform these steps everytime you open MATLAB. However if you want to revert to python 2, then use the above command with the path of the python2 executable.
Hope this helps
  3 Comments
darick barbat
darick barbat on 18 Nov 2021
If you get in the path higher then python@3.8 pyenv will not work

Sign in to comment.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!