Unable to import matlab.engine into PyCharm environment
60 views (last 30 days)
Show older comments
Doug Rank on 8 Jan 2020
Commented: Kasper Grøntved on 13 May 2021
The Mathworks instructions were not sufficient for me, but I was able to follow the advice from this link to patch up the difference and get everything to work.
So now I am able to run a simple program like this:
import numpy as np
import matplotlib as mp
eng = matlab.engine.start_matlab()
squaredNumber = eng.SquareNumber(5)
where SquareNumber is a python package I compiled in Matlab.
However these instructions only appear to work for people with MATLAB installed, not people with just MCR. Specifically, this path doesn't exist for them:
And thus they cannot run the cmd "python setup.py install" there. There is a similar path for MCR:
C:\Program Files\MATLAB\MATLAB Runtime\v93\extern\engines\python
But there is no setup.py file within there.
We have tried copying over the relevant files from C:\Program Files\MATLAB\R2018a\extern\engines\python, and running the command. This however did not resolve the issue and when trying to run the above program, we get the error:
Traceback (most recent call last):
File "C:/Users/rr520253/PycharmProjects/MatlabPythonTest2/SquareNumber/Program.py", line 4, in <module>
ModuleNotFoundError: No module named 'matlab.engine'; 'matlab' is not a package
Process finished with exit code 1
The packages "matlabengineforpython" and "matlabruntimeforpython" do not show up in File->Settings->Project Interpreter (in PyCharm) for the person who only has MCR installed, either (but they do for the person who has MATLAB installed).
One should be able to import the matlab engine with just MCR, right?
Does anyone know what the procedure is to do this in PyCharm? Or do they know what's going wrong here?
Kasper Grøntved on 13 May 2021
I followed these steps:
I went to interpreter settings in Pycharm and copied the interpreter path. I then went to configure the enviroment variables -> enviroment variables -> Path -> New: Here I pasted my interpreter path. Then I opened a terminal inside Pycharm and ran:
python setup.py install
NOTE: to find `matlabroot` type `matlabroot` in MATLAB.
This solved the problem for me. I tried without adding the interpreter path to enviroment variables, but when I did it worked. I'm not an expert so not sure why.
Find more on Call MATLAB from Python in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!Start Hunting!