Skip to content

Instantly share code, notes, and snippets.

@dangom
Last active May 21, 2020 14:32
Show Gist options
  • Save dangom/303879ca649f7a3fe113912d7ffa62d4 to your computer and use it in GitHub Desktop.
Save dangom/303879ca649f7a3fe113912d7ffa62d4 to your computer and use it in GitHub Desktop.
Installing matlab-engine on python 3.6

How to install Matlab Engine on Python 3.6

Preparation

If you’ve tried recently to install matlab engine on a Python 3.6, you’ve seen a message saying that the platform is not supported. That doesn’t make any sense, since Python 3.5 is supported, right?

The problem is that Mathworks hardcodes a list with valid versions, I guess to reduce pressure on their customer service in case something goes wrong with untested versions. Well, that doesn’t mean that we shouldn’t be allowed to try it anyway, right?

All we have to do is modify the offending harcoded files (if we have write permission. On a server we’d have to copy files and change some hardcoded paths as well.)

Assuming we have write permission to change matlab’s install scripts, these are the changes to support 3.6:

Update __init__ files with hardcoded checks.

In the file engines/python/build/lib/matlab/engine/__init__.py , change the list _supported_versions by appending the string ~’3_6’~

_supported_versions = ['2_7', '3_3', '3_4', '3_6']

Do the same for file engines/python/dist/matlab/engine/__init__.py and for engines/python/setup.py

Make a copy of the compiled library

There is a compiled library for your architecture and for your python version. On a Mac, for example, that binary is called /engines/python/dist/matlab/engine/maci64/matlabengineforpython3_4.so.

Make a copy and rename it to your python version:

engdir=engines/python/dist/matlab/engine/maci64
cp ${engdir}/matlabengineforpython3_4.so ${engdir}//matlabengineforpython3_6.so

Open the binary in any binary editor and change all references from 3.4 to 3.6 and all references from 3_4 to 3_6. If everything goes well, running the following command on the extern/engines/python directory should return only 3 entries:

find /Applications/MATLAB_R2015b.app/extern/engines/python -type f -exec grep -l "3_4" {} \;

Installation

To install, simply follow the instructions in the Matlab website:

python3 setup.py install

Test installation

Fire up your python3.6 and try the following:

import sys
print(sys.version)

import matlab.engine
eng = matlab.engine.start_matlab()
print(eng.sqrt(4.))
@dangom
Copy link
Author

dangom commented Nov 22, 2019

thank you for the post, but how do you run an existing matlab file from Python ?

https://www.mathworks.com/help/matlab/matlab_external/call-user-script-and-function-from-python.html

@Farzadtb
Copy link

Farzadtb commented Nov 22, 2019 via email

@ChaoliSun
Copy link

Thanks so much! It helps me to solve my problem perfectly!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment