MATLAB Answers

Unable to import matlab.engine into PyCharm environment

65 views (last 30 days)
Doug Rank
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
import matlab.engine
import SquareNumber
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:
C:\Program Files\MATLAB\R2018a\extern\engines\python\build\lib
And thus they cannot run the cmd "python install" there. There is a similar path for MCR:
C:\Program Files\MATLAB\MATLAB Runtime\v93\extern\engines\python
But there is no 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:
C:\Users\XXXX\PycharmProjects\MatlabPythonTest2\venv\Scripts\python.exe C:/Users/XXXX/PycharmProjects/MatlabPythonTest2/SquareNumber/
Traceback (most recent call last):
File "C:/Users/rr520253/PycharmProjects/MatlabPythonTest2/SquareNumber/", line 4, in <module>
import matlab.engine
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?
  1 Comment
Kasper Grøntved
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:
cd "matlabroot\extern\engines\python"
python 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.

Sign in to comment.

Answers (0)

Community Treasure Hunt

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

Start Hunting!